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

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

    You can solve by using two techniques.

    • The approach suggested by @nathanvda i.e. checking the created_at and updated_at. If they are same, the record is newly created, else its an update.

    • By using virtual attributes in the model. Steps are:

      • Add a field in the model with the code attr_accessor newly_created
      • Update the same in the before_create and before_update callbacks as

        def before_create (record)
            record.newly_created = true
        end
        
        def before_update (record)
            record.newly_created = false
        end
        

提交回复
热议问题