Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip after_commit on destroy in rails

I'd like to skip the after_commit callback when destroying an object, without specifying explicitly a list of methods using the on syntax. I.e. something like:

after_commit :foo, except: [:destroy]
like image 964
dimid Avatar asked Jun 30 '16 08:06

dimid


2 Answers

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.

like image 163
johnhamnavoe Avatar answered Oct 02 '22 09:10

johnhamnavoe


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

like image 37
Viktor Benei Avatar answered Oct 02 '22 08:10

Viktor Benei