缓存has_many通过的ActiveRecord对象:

时间:2014-01-15 19:57:22

标签: ruby-on-rails ruby caching marshalling dalli

当我尝试缓存具有ActiveRecord关系的has_many through:对象时,在重新加载或保存之前,我无法缓存该对象。

person.rb:

class Person < ActiveRecord::Base
  attr_accessible :name

  has_many :person_locations
  has_many :locations, through: :person_locations

  has_many :person_items
  has_many :items, through: :person_items
end

person_item.rb:

class PersonItem < ActiveRecord::Base
  attr_accessible :item_id, :person_id

  belongs_to :item
  belongs_to :person
end

item.rb的:

class Item < ActiveRecord::Base
  attr_accessible :description

  has_many :person_items
  has_many :people, through: :person_items
end

控制台:

p = Person.create
p.items << Item.create
Rails.cache.write Time.now, p
=> false

#now if I save or reload p
p.save # or p.reload
Rails.cache.write Time.now, p
=> truthy

Marshal步骤失败。因此,Marshal.dump(p)会因TypeError: can't dump hash with default proc错误而失败。

如果我只在内存中使用p(使用new而不是create),我可以写入缓存。

p = Person.new
p.items << Item.new
Rails.cache.write Time.now, p

任何想法为什么缓存此ActiveRecord对象失败了?

Rails:3.2.14

达利:2.7

Ruby:1.9.3-p392

修改

另请参阅:Dalli: You are trying to cache a Ruby object which cannot be serialized to memcached

1 个答案:

答案 0 :(得分:0)