Rails cache with where clause

2019-08-08 09:56发布

Model

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

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.

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

1条回答
时光不老,我们不散
2楼-- · 2019-08-08 10:34

It will work with:

where(foreign_id: q).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.

查看更多
登录 后发表回答