我有一个模型对象(假设父)与另一个模型对象(儿童)一的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,ATT以),新的儿童加入的ATT,那些在ATT以集合添加before_update期间不可用(self.children返回老集合)。

有没有什么办法来检索,而不与accepts_nested_attributes_for搞乱新的?

有帮助吗?

解决方案

在描述我的作品有什么使用Rails 2.3.2。我想你可能无法正确分配给父母的孩子。孩子们在更新后更新?

accepts_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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top