I have an expensive .find() ActiveRecord query in Rails that I want to cache but can't:
E.g., running:
Rails.cache.fetch("beneficiary/1") { Beneficiary.find(1) }
will do nothing to cache the result. Instead it will continue to result in a database query being executed to bring in the multiple tables that a Beneficiary object needs in order for its ActiveRecord object attributes to be instantiated correctly. I want to store the result of that instantiation to prevent another database query.
My suspicion is that memcache is only saving an ActiveRecord::Relation as its return value, which is why cache hits still cause new db queries.
For ActiveRecord collections, the workaround has been to use .to_a
or .all
on ActiveRecord::Relation's to force memcache to save its result. But that doesn't work if the AR query is .find()
How do I cache the result of .find()
?