使用where子句的Rails缓存 [英] Rails cache with where clause

查看:58
本文介绍了使用where子句的Rails缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

型号

class Line < ActiveRecord::Base
   attr_accessible :num, :foreign_id

   def self.cached_foreign(q)
       Rails.cache.fetch([name,"foreign"+q.to_s]) { where(:foreign_id => q) }
   end

end

对于上述模型,当 Line.cached_foreign(1)重复运行时,它总是执行sql语句.

For the above model, when Line.cached_foreign(1) is run repeatedly it always executes the sql statement.

这是怎么了?理想情况下,它应该返回来自缓存的重复调用.

What is wrong here? Ideally, it should return repeated calls from cache.

这似乎在使用 find 时很好用,但在使用 where 时却没有.

This seems to work fine when using find but not when using where.

推荐答案

它适用于:

where(foreign_id: q).all

这是因为不带 .all 的语句是延迟计算的,因此在缓存中存储了代理对象,该代理对象在真正需要时会进行评估.如果添加 .all ,则会将实际的记录集存储在缓存中.

It's because statement without .all is lazily evaluated, so in your cache you store proxy object, which is evaluated when it's really needed. If you add .all, you store actual set of records in your cache.

这篇关于使用where子句的Rails缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆