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?
沒錯,只是測試它,並且你的版本可以工作。問題是我依靠孩子數,這返回了舊數。 children.count和children.all.size都返回0,而使用each的實際迭代則打印元素。有關獲得實際數量的任何想法? – 2010-01-07 19:06:17
那麼,請求大小工作之前迭代連接,我會採用這種方法。 – 2010-01-07 19:18:29
這很奇怪。 children.size工作,但不是children.all.size或children.count。 小心依靠伯爵。如果您要移除項目,計數將會關閉,因爲它仍會計入標記爲刪除的項目。你需要做些像children.reject(&:marked_for_deletion).count – EmFi 2010-01-07 19:19:19