Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/54.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails ActiveRecord:如何设置;改为;模型的属性?_Ruby On Rails_Ruby_Activerecord - Fatal编程技术网

Ruby on rails ActiveRecord:如何设置;改为;模型的属性?

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

对于ActiveRecord中的每个模型,似乎都有一个名为“changed”的私有属性,它是一个数组,列出了自从数据库检索记录以来已更改的所有字段

例如:

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