2012-01-15 42 views
6

我正在使用Rails 3.1.0,並且我只想在某些條件滿足的情況下「觸摸」belongs_to關聯的父模型。只有在滿足某些條件的情況下,如何「觸摸」「belongs_to」關聯的父模型?

例如,在這個時候,我有:

belongs_to :article, 
    :touch => true 

我想「碰」父模型只有當它是「公共」。也就是說,Article類有一個名爲access@article.access =>publicprivate)的屬性,我想之前「接觸」來檢查這個值:如果此值public,然後「碰」吧!

是否可以在belongs_to關聯聲明中「直接」?如果是這樣,怎麼樣?

回答

4

就像你說的你可以試試拉姆達但我不確定它是否會工作。事情是這樣的:

belongs_to :article, :touch => Proc.new{|o| o.article && o.article.public } 

按照implementation也許你可以嘗試在proc返回nil,而不是false

belongs_to :article, :touch => Proc.new{|o| o.article && o.article.public ? true : nil } 

如果這不工作使用之前保存時,它的不可用回調如下:

class Model < ActiveRecord::Base 
    belongs_to :article 

    before_save :touch_public_parent 

    def touch_public_parent 
    article.touch if article && article.public? 
    end 
end 

讓我知道如果您有任何問題。

更新#1

相關部分從add_touch_callbacks

if touch_attribute == true 
    association.touch unless association.nil? 
else 
    association.touch(touch_attribute) unless association.nil? 
end 

所以,如果你通過真實的,那麼確實就updated_at屬性簡單的觸摸。如果您傳遞字段名稱,則會更新該字段,除非您通過nil。如果你通過零不會更新什麼。這就是爲什麼我說,也許你可以嘗試第二版belongs_to關聯。

+0

沒有與你在答案中鏈接的add_touch_callbacks方法相關的文檔...你能說一些關於它的更多信息嗎(例如:它是如何工作的)? – Backo 2012-01-16 04:48:14

+0

@Backo當然,請看我最新的答案。 – dombesz 2012-01-16 09:32:05

+0

非常感謝。見下一個問題/答案! – Backo 2012-01-16 11:18:23

0

我不認爲你可以在belongs_to關聯中應用觸摸條件。

有一種方法是有點哈克但有belongs_to的關聯直接合作,

這可能不是推薦的方式

 
class YourModel 
    belongs_to :article 
    belongs_to :public_article, :class_name=> "Article", 
      :foreign_key => "article_id", 
      :conditions => {:public => true} , :touch => true 
end 
+0

是否可以在':touch'選項值中使用'Proc' /'lambda'? – Backo 2012-01-15 17:31:10

+0

不,你不能使用proc或lambda,從文檔引用「:touch =>如果爲true,當這個記錄被保存或銷燬時,關聯的對象將被觸及(updated_at/on屬性設置爲現在)。如果您指定了一個符號,那麼除了updated_at/on屬性之外,該屬性將使用當前時間更新。「 – 2012-01-15 18:05:55

+0

我剛剛打開另一個問題,以達到另一個解決方案:http://stackoverflow.com/questions/8872045/there-is-a-way-to-handle-after-save-and-after-destroy-equally。 – Backo 2012-01-15 18:10:04

相關問題