2010-01-07 45 views
4

我有一個模型對象(讓我們說父)與另一個模型對象(Child)上的has_many關聯。如何在before_update回調中處理activerecord嵌套屬性

class Parent < ActiveRecord::Base 
    has_many :children 
    accepts_nested_attributes_for :children 
end 

class Child < ActiveRecord::Base 
    belongs_to :parent 
end 

在家長,我想在before_update回調添加代碼來設置基於其子計算的屬性。

我一直在遇到的問題是,當我使用方法Parent.update(id,atts),爲新的孩子添加atts時,添加到atts集合中的那些在before_update期間不可用(self.children返回舊集合)。

有沒有什麼辦法可以檢索新的,而不會搞亂accept_nested_attributes_for?

回答

3

你描述的是什麼在Rails 2.3.2中適用於我。我想你可能不會正確地分配給父母的孩子。更新後是否更新了兒童?

accep_nested_attributes_for,如您的問題所用,在父級上創建child_attributes編寫器。我有你想要更新的感覺:孩子而不是:children_attributes。

這個工程使用的模型所描述的,這下before_update回調:

before_update :list_childrens_names 
def list_childrens_names 
    children.each{|child| puts child.name} 
end 

這些命令的控制檯:

Parent.create # => Parent(id => 1) 
Parent.update(1, :childrens_attributes => 
    [{:name => "Jimmy"}, {:name => "Julie"}]) 

產生這樣的輸出:

Jimmy 
Julie 
+1

沒錯,只是測試它,並且你的版本可以工作。問題是我依靠孩子數,這返回了舊數。 children.count和children.all.size都返回0,而使用each的實際迭代則打印元素。有關獲得實際數量的任何想法? – 2010-01-07 19:06:17

+1

那麼,請求大小工作之前迭代連接,我會採用這種方法。 – 2010-01-07 19:18:29

+2

這很奇怪。 children.size工作,但不是children.all.size或children.count。 小心依靠伯爵。如果您要移除項目,計數將會關閉,因爲它仍會計入標記爲刪除的項目。你需要做些像children.reject(&:marked_for_deletion).count – EmFi 2010-01-07 19:19:19