How to determine if a record is just created or updated in after_save

后端 未结 8 1183
失恋的感觉
失恋的感觉 2020-12-23 08:44

The #new_record? function determines if a record has been saved. But it is always false in the after_save hook. Is there a way to determine whether the record i

8条回答
  •  礼貌的吻别
    2020-12-23 09:29

    Since the object has already been saved, you would you need to look at the previous changes. The ID should only change after a create.

    # true if this is a new record
    @object.previous_changes[:id].any?
    

    There is also an instance variable @new_record_before_save. You can access that by doing the following:

    # true if this is a new record
    @object.instance_variable_get(:@new_record_before_save)
    

    Both are pretty ugly, but they would allow you to know whether the object has been newly created. Hope that helps!

提交回复
热议问题