How to capture changes in after_commit

Updated . Posted . Visible to the public.

Your after_commit callbacks will not know about changes, as Rails discards them when committing.

The linked article shows a clever trick to work around that: It uses an after_save method that looks at changes and writes its decision to an instance variable. That instance variable can then be used in the after_commit method.

Note that while callbacks like after_save are not affected, there are valid reasons for using only after_commit, and not after_save. Enqueueing a Sidekiq job is just one of them.

Rails 5+

You can use saved_change_to_attribute? and previous_changes[:attribute] in after_commit callbacks.

See ActiveModel::Dirty Show archive.org snapshot

Profile picture of Arne Hartherz
Arne Hartherz
Last edit
Judith Roth
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2015-07-22 10:08)