Ruby on rails 3 如何从缓存实例化ActiveRecord模型?

Ruby on rails 3 如何从缓存实例化ActiveRecord模型?,ruby-on-rails-3,caching,activerecord,Ruby On Rails 3,Caching,Activerecord,我正在向Rails应用程序添加缓存,我正在做的一件事是使用.new方法(而不是.create)实例化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

我正在向Rails应用程序添加缓存,我正在做的一件事是使用
.new
方法(而不是
.create
)实例化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这个实际值是指数据库中已经存在的行,以便它更新该行而不是抛出和异常?

我需要的答案可以在
lib/active\u record/base.rb
中找到。我需要用
new_record
设置为
false
初始化对象,方法是分配对象,然后用
init_
初始化它。请注意,您需要使用特殊的
序列化的_属性定义的编码器正确地序列化这些属性

请注意,我使用的是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

很难理解你想做什么。