问题
When I try to cache an ActiveRecord
object that has a has_many through:
relationship, I can't cache the object until I reload or save it.
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
Console:
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
It fails at the Marshal
step. So Marshal.dump(p)
would fail with the TypeError: can't dump hash with default proc
error.
If I just make p
in memory (using new
instead of create
) I can write to the cache.
p = Person.new
p.items << Item.new
Rails.cache.write Time.now, p
Any idea why cacheing this ActiveRecord
object is failing?
Rails: 3.2.14
Dalli: 2.7
Ruby: 1.9.3-p392
EDIT
See also: Dalli: You are trying to cache a Ruby object which cannot be serialized to memcached
回答1:
Turns out it is a problem with squeel
.
https://github.com/activerecord-hackery/squeel/issues/232
来源:https://stackoverflow.com/questions/21146983/cacheing-an-activerecord-object-that-has-many-through