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?

Answers


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

Need Your Help

Is there, or is there ever going to be, a conditional operator in Delphi?

delphi delphi-2009 language-features conditional-operator

I kept my hands off Delphi for too long, I guess; busied myself with Java and PHP a lot over the last couple of years. Now, when I got back to doing a little Delphi job, I realised I really miss the

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.