如何确定一条记录是刚刚在after_save中创建还是更新 [英] How to determine if a record is just created or updated in after_save

查看:10
本文介绍了如何确定一条记录是刚刚在after_save中创建还是更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#new_record?函数确定记录是否已保存.但它在 after_save 钩子中总是假的.有没有办法确定记录是新创建的记录还是更新的旧记录?

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 is a newly created record or an old one from update?

我希望不要使用其他回调(例如 before_create)在模型中设置标志或要求对数据库进行另一个查询.

I'm hoping not to use another callback such as before_create to set a flag in the model or require another query into the db.

任何建议表示赞赏.

需要在 after_save 钩子中确定它,对于我的特定用例,没有 updated_atupdated_on 时间戳

Need to determine it in after_save hook, and for my particular use case, there is no updated_at or updated_on timestamp

推荐答案

我希望将其用于 after_save 回调.

I was looking to use this for an after_save callback.

一个更简单的解决方案是使用 id_changed?(因为它不会在 update 上改变)甚至 created_at_changed? 如果时间戳列是存在.

A simpler solution is to use id_changed? (since it won't change on update) or even created_at_changed? if timestamp columns are present.

更新:正如@mitsy 指出的那样,如果在回调之外需要此检查,则使用 id_previously_changed?.请参阅文档.

Update: As @mitsy points out, if this check is needed outside of callbacks then use id_previously_changed?. See docs.

这篇关于如何确定一条记录是刚刚在after_save中创建还是更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆