Cacheing an ActiveRecord Object that has_many through:

自作多情 提交于 2019-12-24 21:50:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!