Question

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

Was it helpful?

Solution

Turns out it is a problem with squeel.

https://github.com/activerecord-hackery/squeel/issues/232

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top