4

我有一个模型对象(比方说父)与另一个模型对象(子)上的 has_many 关联。

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的情况下检索新的?

4

1 回答 1

3

你所描述的对我来说适用于 Rails 2.3.2。我认为您可能没有正确分配给父母的孩子。更新后孩子有更新吗?

如您的问题中所使用的,accepts_nested_attributes_for 在父级上创建一个 child_attributes 编写器。我感觉您正在尝试更新 :children 而不是 :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
于 2010-01-07T15:49:25.603 回答