Reputation: 16771
So I have an after_update
callback in an ActiveRecord
model to notify an external service. This should only be called if a couple of attributes are being updated. So I encapsulated the saved_change_to_attribute?
calls in a method that is then used in the callback filter:
after_update :tell_service!, if: :update_for_service?
def update_for_service?
saved_change_to_name? ||
saved_change_to_city?
end
Now update_for_service?
always returns false
and I don't understand why.
In the console:
> p = Person.last
> p.name = 'Tom'
> p.save
true
> p.saved_change_to_name?
true
> p.update_for_service?
false
What is going on here?
Upvotes: 5
Views: 4607
Reputation: 80140
This is due to when after_update
runs in the callback lifecycle. This answer by pan.goth explains:
after_save
,after_create
,after_update
are called within the transaction block, so they will be executed before executing the SQL statement.If you want to do something when the statement execution is completed, you should use after_commit callback.
Upvotes: 3