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

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

提交回复
热议问题