【问题标题】:Querying the cache in rails still runs a call against the DB在 rails 中查询缓存仍然会针对数据库运行调用
【发布时间】:2012-07-27 17:17:45
【问题描述】:

我可能在这里遗漏了一些非常简单的东西,但不明白是什么。

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

控制器代码:

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

我可以看到,在我的第二次调用中,我到达了 if 块,而不是 else,但是任何时候我试图触摸产品(比如渲染它),我也会看到一个对 DB 的活动记录调用。

我错过了什么?

【问题讨论】:

  • 不是答案,但考虑使用fetch 而不是自己进行读写操作。

标签: ruby-on-rails ruby caching activerecord


【解决方案1】:

线

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

返回一个ActiveRecord::Relation,但不会访问数据库,除非调用了 kicker 方法。

虽然我仍然建议使用上面评论中提到的fetch,但请尝试将行更改为:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-19
    • 2012-09-11
    • 1970-01-01
    • 1970-01-01
    • 2020-09-26
    • 1970-01-01
    • 2015-11-12
    • 1970-01-01
    相关资源
    最近更新 更多