如何在Rails中获取属性的原始值 [英] How to get the original value of an attribute in Rails
问题描述
有没有办法获取 ActiveRecord 属性的原始值(=从数据库加载的值)?
is there a way to get the original value that an ActiveRecord attribute (=the value that was loaded from the database)?
我想在观察者身上有这样的东西
I want something like this in an observer
before_save object
do_something_with object.original_name
end
任务是在更新时从哈希表中删除对象(实际上是将其移动到表中的另一个键).
The task is to remove the object from a hash table (in fact, move it to another key in the table) upon updating.
推荐答案
Rails 5.1 之前
将 _was
附加到您的属性将为您提供以前的值.
Before rails 5.1
Appending _was
to your attribute will give you the previous value.
从下面 Lucas Andrade 的回答中复制:https://stackoverflow.com/a/50973808/9359123
附加 _was
在 rails 5.1 中被弃用,现在你应该附加 _before_last_save
Appending _was
is deprecated in rails 5.1, now you should append _before_last_save
类似于:
before_save object
do_something_with object.name_before_last_save
end
将返回上次保存在数据库之前的名称值(适用于保存和创建)
根据文档,_was
和 _before_last_save
之间的区别:
Will return the name value before your last save at database (works for save and create)
The difference between _was
and _before_last_save
according to the documentation:
_was 来源 来自文档
def attribute_was(attr)
attribute_changed?(attr) ? changed_attributes[attr] : __send__(attr)
end
_before_last_save 来源来自文档
def attribute_before_last_save(attr_name)
mutations_before_last_save.original_value(attr_name)
end
这篇关于如何在Rails中获取属性的原始值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!