如何确定模型/嵌套模型中的任何字段是否发生更改?
是否有一些快速方法可以找出模型的任何字段或其嵌套模型(也称为关联)的任何字段是否发生更改?
Is there some quick way to find out if any of a model's fields or any fields of it's nested models (a.k.a. associations) changed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
要查看 ActiveRecord 对象是否已更改,您可以调用:
要查看特定属性是否已更改,您可以执行以下操作:
其中 attr 是您要检查的属性。
要检查嵌套模型是否发生更改,您可以执行以下操作:
To see if a ActiveRecord object has changed, you can call:
To see if a specific attribute was changed, you can do:
where attr is the attribute you want to check.
To check for if a nested model changed, you can just do:
我知道这是一个老问题,但最近遇到了同样的情况。
即使在保存对象后,您也可以使用
previous_changes
方法获取嵌套模型的所有更改。这将列出嵌套模型中的所有更改以及旧值和新值。
I know this is old question but recently came across same situation.
You can get all changes for your nested model using
previous_changes
method even after saving the object.This will list all changes in the nested model along with old and new value.
在 5.1 + 中,以下内容对我有用:
saved_changes?
会让您知道您的对象是否已更改:saved_changes
会让您知道哪些字段发生了更改,之前的值和之后的值每个字段的值:with 5.1 + the following works for me:
saved_changes?
will let you know if your object has changed:saved_changes
will let you know which fields changed, the before value and the after value for each field:您可以通过调用确定对象是否已更改但尚未保存:
您还可以确定单个属性是否已更改(假设您有一个
first_name
属性):就嵌套模型而言,我认为您必须分别对它们分别调用
changed?
。You can determine if an object has changed but not yet been saved by calling:
You can also determine if individual attributes have changed (say you have a
first_name
attribute):As far as nested models go, I think you'd have to call
changed?
on them each individually.对于
accepts_nested_attributes_for
你可以做model.things.detect { |thing|东西.id.空白? }
for
accepts_nested_attributes_for
you can domodel.things.detect { |thing| thing.id.blank? }