开发者

How to process new children in before_update callback for activerecord nested attributes

I have a model object (let's say Parent) with a has_many association on another model object (Child).

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

class Child < ActiveRecord::Base
    belongs_to :parent
end

On Parent, I want to add code on the before_update callback to set a calculated attribute开发者_运维百科 based on its children.

The problem I've been running into is that when I use the method Parent.update(id, atts), adding atts for new children, those added in the atts collection are not available during before_update (self.children returns the old collection).

Is there any way to retrieve the new one without messing with the accepts_nested_attributes_for?


What you describe works for me with Rails 2.3.2. I think you may not be assigning to a parent's children properly. Are the children updated after the update?

accepts_nested_attributes_for, as used in your question, creates a child_attributes writer on the parent. I have the feeling you're trying to update :children as opposed to :children_attributes.

This works using your models as described and this following before_update callback:

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

these commands in the console:

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

produce this output:

Jimmy
Julie
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜