Read more

How to capture changes in after_commit

Arne Hartherz
July 22, 2015Software engineer at makandra GmbH

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

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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

Posted by Arne Hartherz to makandra dev (2015-07-22 12:08)