2012-01-27 18 views
1

我正在向我的Rails應用添加緩存,我正在做的其中一件事是使用.new方法(而不是.create)實例化ActiveRecord模型,因此它不嘗試創建新行。如何從緩存實例化ActiveRecord模型?

例如,如果我加入這我的模型:

def from_json(json) 
    o = self.new 
    ActiveSupport::JSON.decode(json).each do |k, v| 
    # NOTE: I am doing this instead of sending all the params to .new 
    #  because Rails won't let me bulk update protected attributes 
    o.send(k + '=', v) 
    end 
    o 
end 

然後實例從緩存中的對象:

o = Foo.from_json(redis.get(key)) 

一切似乎運作良好,直到我試圖改變一個字段:

o.bar = "spam and eggs" 
o.save 

我收到一個異常,說這是一個重複的條目。

如何告訴ActiveRecord此實際引用數據庫中已存在的行,以便它更新該行而不是拋出和異常?

+0

真的很難理解你想要做什麼。 – lucapette 2012-01-27 17:35:32

回答

3

我需要的答案在lib/active_record/base.rb中找到。我需要初始化new_record設置爲false的對象,並且執行此操作的方法是分配對象,然後用init_with對其進行初始化。請注意,您需要使用其定義的編碼器正確序列化特殊serialized_attributes

請注意,我正在使用Rail 3.1。

def serialize_for_cache 
    h = self.attributes.clone 
    self.class.serialized_attributes.each do |key, coder| 
    h[key] = coder.dump(h[key]) 
    end 
    ActiveSupport::JSON.encode(h) 
end 

def deserialize_from_cache(json) 
    self.allocate.init_with('attributes' => ActiveSupport::JSON.decode(json)) 
end