How to determine if any field in a model / nested

2020-02-18 04:05发布

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?

4条回答
孤傲高冷的网名
2楼-- · 2020-02-18 04:24

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]}
查看更多
够拽才男人
3楼-- · 2020-02-18 04:34

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.

查看更多
狗以群分
4楼-- · 2020-02-18 04:36

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.

查看更多
别忘想泡老子
5楼-- · 2020-02-18 04:39

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?
查看更多
登录 后发表回答