Skip after_commit on destroy in rails

I've found a way to do it on Ruby Tips:

after_commit :foo, if: :persisted?

or for more complex conditions:

after_commit, :foo, if: Proc.new {|record| record.persisted? && [...]}

The shortest solution is the one shared by @dimid , but I believe, right now the pragmatic approach is to list the events you want to handle and just leave out :destroy. There are 3 available :on options right now, :create, :update and :destroy.

To execute foo on create & update:

after_commit :foo, :on => [:create, :update]

Alternatively:

after_commit :foo, on: :create after_commit :foo, on: :update

Or since Rails 5 (https://github.com/rails/rails/pull/22516) it's also possible to:

after_create_commit :foo after_update_commit :foo


In Rails 6 you can use after_save_commit as shortcut to after_commit :foo, on: [:create, :update]

after_save_commit :foo

This will skip the callback on destroy.