如何在ActiveRecord中缓存.find()的结果?

时间:2017-03-15 20:58:33

标签: ruby-on-rails caching activerecord

我在Rails中有一个昂贵的.find()ActiveRecord查询,我想缓存但不能:

,例如,跑步:

Rails.cache.fetch("beneficiary/1") { Beneficiary.find(1) }

无法缓存结果。相反,它将继续导致执行数据库查询以引入Beneficiary对象所需的多个表,以便正确实例化其ActiveRecord对象属性。我想存储该实例化的结果以防止另一个数据库查询。

我怀疑是memcache is only saving an ActiveRecord::Relation as its return value,这就是为什么缓存命中仍会导致新的数据库查询。

对于ActiveRecord集合,解决方法是在ActiveRecord :: Relation上使用.to_a.all来强制memcache保存其结果。但如果AR查询为.find()

,则无效

如何缓存.find()的结果?

0 个答案:

没有答案