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

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

    I think transaction_include_action? is what you are after. It gives a reliable indication of the specific transaction in process (verified in 3.0.8).

    Formally, it determines if a transaction included an action for :create, :update, or :destroy. Used in filtering callbacks.

    class Item < ActiveRecord::Base
      after_commit lambda {    
        Rails.logger.info "transaction_include_action?(:create): #{transaction_include_action?(:create)}"
        Rails.logger.info "transaction_include_action?(:destroy): #{transaction_include_action?(:destroy)}"
        Rails.logger.info "transaction_include_action?(:update): #{transaction_include_action?(:update)}"
      }
    end
    

    Also of interest may be transaction_record_state which can be used to determine if a record was created or destroyed in a transaction. State should be one of :new_record or :destroyed.

    Update for Rails 4

    For those seeking to solve the problem in Rails 4, this method is now deprecated, you should use transaction_include_any_action? which accepts an array of actions.

    Usage Example:

    transaction_include_any_action?([:create])
    

提交回复
热议问题