2013-09-23 48 views
1

對於ActiveRecord中的每個模型,似乎都有一個名爲「changed」的私有屬性,它是一個數組,列出了自從您從數據庫檢索記錄後發生更改的所有字段。ActiveRecord:如何設置模型的「更改」屬性?

例子:

a = Article.find(1) 
a.shares = 10 
a.url = "TEST" 

a.changed ["shares", "url"] 

反正有沒有設置這個自己 「改爲」 財產?我知道這聽起來像是hacky/klunky,但我正在做一些非常不尋常的事情,那就是使用Redis來緩存/檢索對象。

回答

2

ActiveModel::Dirty#changed返回@changed_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_attributes=,您可以通過力設定的實例變量:

a.instance_variable_set(:@changed_attributes, {"foo" => "bar"}) 
a.changed #=> ["foo"] 
+0

正是我在找的東西。謝謝! –

1

查看此示例來自:Dirty Attributes

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 

所以,如果你有一個屬性foo,並且想要「更改」,那就叫foo_will_change!