Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails nested attributes children callbacks aren't fired

Tags:

I'm running into a bizarre issue where children callbacks aren't fired when the parent is updated...

I have the following model setup:

class Budget < ActiveRecord::Base   has_many :line_items   accepts_nested_attributes_for :line_items end 

 

class LineItem < ActiveRecord::Base   belongs_to :budget    before_save :update_totals    private   def update_totals     self.some_field = value   end end 

In my form, I have the fields nested (built using fields_for):

= form_for @budget do |f|   = f.text_field :name   = f.fields_for :line_items do |ff|     = ff.text_field :amount 

Why is the update_totals callback on the child never fired / what can I do to make it fire?

like image 961
sethvargo Avatar asked Feb 20 '12 09:02

sethvargo


1 Answers

I had the same issue. before_save callback is not called when the model is not changed.

You're updating line_items, not the budget, so rails thinks that it is not updated and doesn't call save for it.

You need to change before_save to after_validation so it will be called even if model has no changed attributes. And when in this callback you change some attributes, rails will see that your model had changed and will call save.

like image 136
Anton Dieterle Avatar answered Nov 22 '22 05:11

Anton Dieterle