如何确定模型/嵌套模型中的任何字段是否发生更改?

发布于 2024-10-31 14:46:17 字数 52 浏览 1 评论 0原文

是否有一些快速方法可以找出模型的任何字段或其嵌套模型(也称为关联)的任何字段是否发生更改?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

楠木可依 2024-11-07 14:46:17

要查看 ActiveRecord 对象是否已更改,您可以调用:

instance.changed?

要查看特定属性是否已更改,您可以执行以下操作:

instance.attr_changed?

其中 attr 是您要检查的属性。

要检查嵌套模型是否发生更改,您可以执行以下操作:

instance.nested_model.changed?

To see if a ActiveRecord object has changed, you can call:

instance.changed?

To see if a specific attribute was changed, you can do:

instance.attr_changed?

where attr is the attribute you want to check.

To check for if a nested model changed, you can just do:

instance.nested_model.changed?
空名 2024-11-07 14:46:17

我知道这是一个老问题,但最近遇到了同样的情况。

即使在保存对象后,您也可以使用 previous_changes 方法获取嵌套模型的所有更改。

parent_model_object.nested_model_name.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.

parent_model_object.nested_model_name.previous_changes

This will list all changes in the nested model along with old and new value.

〃温暖了心ぐ 2024-11-07 14:46:17

在 5.1 + 中,以下内容对我有用:

saved_changes? 会让您知道您的对象是否已更改:

my_object.saved_changes?
=> true

saved_changes 会让您知道哪些字段发生了更改,之前的值和之后的值每个字段的值:

my_object.saved_changes
=> {"first_name"=>['Jim', 'Jimmy'], "updated_at"=>[Thu, 06 Dec 2018 18:45:00 UTC +00:00, Thu, 06 Dec 2018 18:52:44 UTC +00:00]}

with 5.1 + the following works for me:

saved_changes? will let you know if your object has changed:

my_object.saved_changes?
=> true

saved_changes will let you know which fields changed, the before value and the after value for each field:

my_object.saved_changes
=> {"first_name"=>['Jim', 'Jimmy'], "updated_at"=>[Thu, 06 Dec 2018 18:45:00 UTC +00:00, Thu, 06 Dec 2018 18:52:44 UTC +00:00]}
-黛色若梦 2024-11-07 14:46:17

您可以通过调用确定对象是否已更改但尚未保存:

my_object.changed?

您还可以确定单个属性是否已更改(假设您有一个 first_name 属性):

my_object.first_name_changed?

就嵌套模型而言,我认为您必须分别对它们分别调用 changed?

You can determine if an object has changed but not yet been saved by calling:

my_object.changed?

You can also determine if individual attributes have changed (say you have a first_name attribute):

my_object.first_name_changed?

As far as nested models go, I think you'd have to call changed? on them each individually.

无声无音无过去 2024-11-07 14:46:17

对于 accepts_nested_attributes_for 你可以做 model.things.detect { |thing|东西.id.空白? }

for accepts_nested_attributes_for you can do model.things.detect { |thing| thing.id.blank? }

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文