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?
I had the same issue.
before_savecallback is not called when the model is not changed.You’re updating
line_items, not thebudget, so rails thinks that it is not updated and doesn’t callsavefor it.You need to change
before_savetoafter_validationso 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 callsave.