Rails 3: How to identify after_commit action in observers? (create/update/destroy)

前端 未结 9 1297
慢半拍i
慢半拍i 2021-01-30 02:17

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

相关标签:
9条回答
  • 2021-01-30 02:54

    Take a look at the test code: https://github.com/rails/rails/blob/master/activerecord/test/cases/transaction_callbacks_test.rb

    There you can find:

    after_commit(:on => :create)
    after_commit(:on => :update)
    after_commit(:on => :destroy)
    

    and

    after_rollback(:on => :create)
    after_rollback(:on => :update)
    after_rollback(:on => :destroy)
    
    0 讨论(0)
  • 2021-01-30 02:58

    I've learned today that you can do something like this:

    after_commit :do_something, :on => :create
    
    after_commit :do_something, :on => :update
    

    Where do_something is the callback method you want to call on certain actions.

    If you want to call the same callback for update and create, but not destroy, you can also use: after_commit :do_something, :if => :persisted?

    It's really not documented well and I had a hard time Googling it. Luckily, I know a few brilliant people. Hope it helps!

    0 讨论(0)
  • 2021-01-30 03:00

    Based on leenasn idea, I created some modules that makes it possible to use after_commit_on_updateand after_commit_on_create callbacks: https://gist.github.com/2392664

    Usage:

    class User < ActiveRecord::Base
      include AfterCommitCallbacks
      after_commit_on_create :foo
    
      def foo
        puts "foo"
      end
    end
    
    class UserObserver < ActiveRecord::Observer
      def after_commit_on_create(user)
        puts "foo"
      end
    end
    
    0 讨论(0)
提交回复
热议问题