Last Updated: February 25, 2016
·
3.222K
· artchang

“You are trying to cache a Ruby object which cannot be serialized to memcached.”

Rails 3+ lazy loads all queries, so if you're trying to cache an ActiveRecord query, it will not marshall the actual query entries, but the deferred query.

Rails 3+ won't actually execute the query until it's used. This is nice, just in case you're running queries you never need to use, or you have it in a before_filter that is a little too aggressive.

So in order to marshall the actual entries from the query into a cache block, you need to call entries on something like a where lookup.

Rails.cache.fetch key do
    User.where(pro: true).entries
end

The downside is when the key expires or hasn't been cached yet, this will run regardless and not be lazy loaded. Good news is you now have it cached (hopefully smartly with a cache key).