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_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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With