Rails:检查模型是否确实保存在 after_save 中
即使模型没有更改并且没有生成插入/更新查询,ActiveRecord 也会在每次调用 save 方法时调用 after_save 回调。
这实际上是默认行为。在大多数情况下这是可以的。
但是一些 after_save 回调对模型是否实际保存很敏感。
有没有办法确定模型是否确实保存在 after_save 中?
我正在运行以下测试代码:
class Stage < ActiveRecord::Base
after_save do
pp changes
end
end
s = Stage.first
s.name = "q1"
s.save!
ActiveRecord use to call after_save callback each time save method is called even if the model was not changed and no insert/update query spawned.
This is the default behaviour actually. And that is ok in most cases.
But some of the after_save callbacks are sensitive to the thing that if the model was actually saved or not.
Is there a way to determine if the model was actually saved in the after_save?
I am running the following test code:
class Stage < ActiveRecord::Base
after_save do
pp changes
end
end
s = Stage.first
s.name = "q1"
s.save!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
每次成功保存记录时,无论更改如何,ActiveRecord 都会执行 :after_save 回调。
您想知道的是记录是否更改,而不是记录是否保存。
您可以使用
record.changed?
轻松完成此操作ActiveRecord executes :after_save callbacks each time the record is successfully saved regardless it was changed.
What you want to know is if the record is changed, not if the record is saved.
You can easily accomplish this using
record.changed?
保存后,检查保存的对象是否是新对象
After a save, check to see if the object saved is a new object
对于登陆这里的其他人,最新的 Rails 5 有一个模型方法
saved_changes?
和一个相应的方法saved_changes
显示这些更改。For anyone else landing here, latest rails 5 has a model method
saved_changes?
and a corresponding methodsaved_changes
which shows those changes.