6

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?

Jordan Running
  • 102,619
  • 17
  • 182
  • 182
Milind
  • 4,535
  • 2
  • 26
  • 58
  • I am a little confused here. What do you mean by "It's not working". Can you clarify? In your observer, using: @user.do_something if @user.new_record? should work. – Venice Dec 18 '14 at 16:44
  • Can you tell us more about the original problem you're trying to solve? The only hint you give is "to update the count." Please show us the actual code you're using in your model and in your observer. – Jordan Running Dec 18 '14 at 16:51
  • 2
    The 3rd one is not working because in `after_commit` it wouldn't be a `new_record` anymore. – DiegoSalazar Dec 18 '14 at 17:26
  • thanks @diego.greyrobot..using just after_commit will run everytime..so i need to run it only on create in observer ONLY..its always running the code,which is not good performance wise..so how can it resrict it for ONLY create? – Milind Dec 19 '14 at 10:23

3 Answers3

15

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.

Van_Paitin
  • 3,678
  • 2
  • 22
  • 26
6

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

DiegoSalazar
  • 13,361
  • 2
  • 38
  • 55
2

Just FYI the accepted answer does not work in many versions of rails and is a bug. This ticket is referencing a different issue of multiple callbacks with the same name. However, the bug is still there (any after_commit on:create doesn't work) in many rails versions.

'seako' has a workaround to fix this problem if you are running into it

https://github.com/rails/rails/issues/988

after_commit ->(obj) { obj.do_something }, on: :create
Mysrt
  • 3,044
  • 2
  • 17
  • 14