Marshal.dump and load with ActiveRecord

If you aren’t familiar with Marshal.dump and 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.dump and Marshal.load dump and load the association data, as well.

https://gist.github.com/keichan34/6448987

NB: This hack works with Rails 4, but I haven’t tried it on any other versions. YMMV.