当我尝试缓存ActiveRecord具有has_many through:关系的对象时,我无法缓存该对象,直到我重新加载或保存它。
人.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
项目.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对象会失败吗?
导轨:3.2.14
达利:2.7
红宝石:1.9.3-p392
编辑