Ruby on rails ActiveRecord:如何设置;改为;模型的属性?
对于ActiveRecord中的每个模型,似乎都有一个名为“changed”的私有属性,它是一个数组,列出了自从数据库检索记录以来已更改的所有字段 例如:Ruby on rails ActiveRecord:如何设置;改为;模型的属性?,ruby-on-rails,ruby,activerecord,Ruby On Rails,Ruby,Activerecord,对于ActiveRecord中的每个模型,似乎都有一个名为“changed”的私有属性,它是一个数组,列出了自从数据库检索记录以来已更改的所有字段 例如: a = Article.find(1) a.shares = 10 a.url = "TEST" a.changed ["shares", "url"] 是否需要自己设置此“已更改”属性?我知道这听起来很粗糙,但我正在做一件非常不寻常的事情,那就是使用Redis缓存/检索对象。ActiveModel::Dirty#changed返回@ch
a = Article.find(1)
a.shares = 10
a.url = "TEST"
a.changed ["shares", "url"]
是否需要自己设置此“已更改”属性?我知道这听起来很粗糙,但我正在做一件非常不寻常的事情,那就是使用Redis缓存/检索对象。ActiveModel::Dirty#changed
返回@changed\u attributes
散列的键,散列本身返回属性名称及其原始值:
a = Article.find(1)
a.shares = 10
a.url = "TEST"
a.changed #=> ["shares", "url"]
a.changed_attributes #=> {"shares" => 9, "url" => "BEFORE_TEST"}
由于没有setter方法changed\u attributes=
,因此可以强制设置实例变量:
a.instance_variable_set(:@changed_attributes, {"foo" => "bar"})
a.changed #=> ["foo"]
请参见以下示例:
所以,如果你有一个属性
foo
并且想要“改变”,那么只要调用foo\u就会改变代码>正是我想要的。谢谢
class Person
include ActiveModel::Dirty
define_attribute_methods :name
def name
@name
end
def name=(val)
name_will_change! unless val == @name
@name = val
end
def save
@previously_changed = changes
@changed_attributes.clear
end
end