Rails nested attributes children callbacks aren't fired

sethvargo picture sethvargo · Feb 20, 2012 · Viewed 9.9k times · Source

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?

Answer

Anton Dieterle picture Anton Dieterle · Jul 20, 2012

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.