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

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

    This is similar to your 1st approach but it only uses one method (before_save or before_validate to really be safe) and I don't see why this would override any value

    class ItemObserver
      def before_validation(item) # or before_save
        @new_record = item.new_record?
      end
    
      def after_commit(item)
        @new_record ? do_this : do_that
      end
    end
    

    Update

    This solution doesn't work because as stated by @eleano, ItemObserver is a Singleton, it has only one instance. So if 2 Item are saved at the same time @new_record could take its value from item_1 while after_commit is triggered by item_2. To overcome this problem there should be an item.id checking/mapping to "post-synchornize" the 2 callback methods : hackish.

提交回复
热议问题