Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using after_commit only on create

I have a UserObserver with after_commit (changed from after_create to avoid a race condition error that id not found) to update the count. But I know for every create, update is executing the after_commit code (which I knew would happen). How can I run the after_commit only on create? I have few solutions but a bit confused. I've tried:

  1. Using after_commit :do_something, :on => :create in the model.
  2. Checking the created_at and updated_at in the observer; if they're the same, then it's a new record.
  3. Using user.new_record?

I am confused as I want to use 3rd one, but it's not working and I don't know why. I want to use observers only and not the model. Any ideas on this?

like image 388
Milind Avatar asked Aug 24 '26 11:08

Milind


2 Answers

From rails 5, Rails added three new aliases to handle this kind of situation: after_create_commit, after_update_commit, after_destroy_commit

In your own particular case, you can use:

after_create_commit :do_something.

like image 159
Van_Paitin Avatar answered Aug 26 '26 00:08

Van_Paitin


According to the docs using on: :create should work: http://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html#method-i-after_commit

like image 28
DiegoSalazar Avatar answered Aug 26 '26 00:08

DiegoSalazar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!