I have an observer and I am registering an after_commit . How can I find out if it was launched after creation or update? Can I say that the item was destroyed by requesting item.destroyed? but #new_record? does not work because the item was saved.
I was going to solve this problem by adding after_create / after_update and doing something like @action = :create inside and checking @action in after_commit , but it seems like the observer instance is a single, and I can just override the value before it reaches until after_commit . So I solved it in an ugly way by storing the action on the map based on item.id on after_create / update and checking its value on after_commit. Really ugly.
Is there another way?
Update
As @tardate, transaction_include_action? is a good indicator, although it is a private method, and in the observer it should be accessed using #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 check the hell of your watchers (look for test_after_commit gem if you use use_transactional_fixtures), so when you upgrade to the new version of Rails, you will know if it still works.
(verified in 3.2.9)
Update 2
Instead of observers, I now use ActiveSupport :: Concern and after_commit :blah, on: :create works there.
ruby-on-rails ruby-on-rails-3 observer-pattern transactions
elado Aug 30 '11 at 4:26 a.m. 2011-08-30 04:26
source share