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

后端 未结 8 1181
失恋的感觉
失恋的感觉 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:41

    Rails 5.1+ way:

    user = User.new
    user.save!
    user.saved_change_to_attribute?(:id) # => true
    
    0 讨论(0)
  • 2020-12-23 09:43

    Yet another option, for those who do have an updated_at timestamp:

    if created_at == updated_at
      # it's a newly created record
    end
    
    0 讨论(0)
提交回复
热议问题