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

前端 未结 9 1394
慢半拍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 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
    

提交回复
热议问题