2012-07-30 14 views
0

我可能在这里丢失了一些非常简单的东西,但不明白是什么。在rails中查询缓存仍然对数据库运行调用

我试图缓存一个简单的活动记录查询,但每次触摸缓存时,都会再次对数据库运行查询。

控制器代码:

products = Rails.cache.read("search_results") 
if products 
    render :text => products[0].id 
else 
    products = Product.where('name LIKE ?", 'product_name?') 
    Rails.cache.write("search_results", products) 
end 

我可以看到,在我的第二个电话,我得到的,如果块,而不是其他人,而是任何我想要去触摸产品(如渲染它)时我也查看对数据库的有效记录调用。

我错过了什么?

+0

不是答案,但考虑使用['fetch'](http://api.rubyonrails.org/classes/ActiveSupport/Cache/Store.html#method-i-fetch)而不是自己读写。 – x1a4 2012-07-30 02:30:52

回答

5

线

products = Product.where('name LIKE ?", 'product_name?') 

返回ActiveRecord::Relation,但并没有数据库,除非起脚方法被调用就可以了。

虽然我还是会建议使用fetch如上面我的评论中提到,尝试改变行:

这将迫使数据库命中,而查询的实际结果保存到缓存中,而不是关系。

相关问题