当我尝试缓存具有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.7Ruby:1.9.3-p392
修改
另请参阅:Dalli: You are trying to cache a Ruby object which cannot be serialized to memcached