Question

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?

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top