views:

298

answers:

1

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?

+1  A: 

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
EmFi
Yep, just tested it, and your version works. The problem is that I was relying on the children count, which returns the old count. children.count and children.all.size both return 0, while the iteration using each actually prints the elements. Any idea on obtaining the actual count?
Santiago Palladino
Well, iterating the connection before requesting size worked, I'll go with that approach.
Santiago Palladino
EmFi
Good to know, thanks a lot!
Santiago Palladino