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

I have a model object (albeit a Parent) with the 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 

In Parent, I want to add code for the before_update callback to set the computed attribute based on its children.

The problem I am facing is that when I use the Parent.update (id, atts) method, adding atts for new children, those added to the atts collections are not available during before_update (self.children returns the old collection )

Is there a way to get a new one without going into accepts_nested_attributes_for?

+4
source share
1 answer

What you are describing works for me with Rails 2.3.2. I think that you cannot assign parent children correctly. Are children updated after the upgrade?

accepts_nested_attributes_for used in your question creates the parent file child_attributes. I have the feeling that you are trying to update: children, not: children_attributes.

This works using your models, as described, and this subsequent 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"}]) 

output this conclusion:

 Jimmy Julie 
+3
source

All Articles