Reputation: 3005
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
.
Upvotes: 1
Views: 313
Reputation: 51151
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.
Upvotes: 1