If you aren’t familiar with
Marshal.load, you probably should be. It’s used to serialize Ruby objects into binary data – mostly caching.
Now, if you’re trying to implement a Russian-doll caching system with objects, you probably have run into the issue of eager-loading associations using
#includes not being cached.
my_data = Rails.cache.fetch('an_object') do MyData.where(condition: 1).includes(:user).first end my_data.user # On cache miss: # => SELECT "my_datas".* FROM "my_datas" WHERE "condition" = 1 ORDER BY "id" ASC LIMIT 1 # => SELECT "users".* FROM "users" WHERE "id" = 1 # On cache hit: # => SELECT "users".* FROM "users" WHERE "id" = 1
So, I wrote a quick module to make
Marshal.load dump and load the association data, as well.
NB: This hack works with Rails 4, but I haven’t tried it on any other versions. YMMV.