I have an observer and I register an after_commit
callback.
How can I tell whether it was fired after create or update?
I can tell an item was destroyed by asking item.destroyed?
but #new_record?
doesn't work since the item was saved.
I was going to solve it by adding after_create
/after_update
and do something like @action = :create
inside and check the @action
at after_commit
, but it seems that the observer instance is a singleton and I might just override a value before it gets to the after_commit
. So I solved it in an uglier way, storing the action in a map based on the item.id on after_create/update and checking its value on after_commit. Really ugly.
Is there any other way?
Update
As @tardate said, transaction_include_action?
is a good indication, though it's a private method, and in an observer it should be accessed with #send
.
class ProductScoreObserver < ActiveRecord::Observer
observe :product
def after_commit(product)
if product.send(:transaction_include_action?, :destroy)
...
Unfortunately, the :on
option does not work in observers.
Just make sure you test the hell of your observers (look for test_after_commit
gem if you use use_transactional_fixtures) so when you upgrade to new Rails version you'll know if it still works.
(Tested on 3.2.9)
Update 2
Instead of Observers I now use ActiveSupport::Concern and after_commit :blah, on: :create
works there.