如何缓存on Rails的3红宝石查询 [英] How to cache a query in Ruby on Rails 3

查看:89
本文介绍了如何缓存on Rails的3红宝石查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下查询我的应用程序

I have the following query in my application

@categories = Category.joins(:posts).select('distinct categories.*').order('label')

该查询被加载在每一个页面视图,因为类别显示在每一页上。这似乎是混乱的对我,因为类别列表都没有得到更新的频率。有没有一种很巧妙的方法来缓存仅仅是查询?我试图

This query gets loaded on every page view since the categories are displayed on every page. This seems messy to me since the list of categories are not getting updated that often. Is there a nifty way to cache just the query? I have tried

   Category.cache do
      @categories = Category.joins(:posts).select('distinct categories.*').order('label')
    end

但我还是看到每一次查询得到加载从开发日志数据库。

but I still see the query getting loaded every time from the database in the development log.

推荐答案

在你的控制器,你可以尝试这样的:

In your controller, you can try something like:

@categories = Rails.cache.fetch('categories', :expires_in => 24.hours) { Category.joins(:posts).select('distinct categories.*').order('label') }

其中将只读取,以查看是否以下数据块'类别'已经被缓存而没有过期。如果24小时后到期,然后将查询模型并写入新的记录到Rails缓存。

Which will only read to see if the following data block 'categories' has been cached and not expired. If expired after 24 hours, will then query the model and write the new record into Rails cache.

有关详细信息,我也跟着下面的指南

For more information, I followed the following guide.

试试吧。我有工作这种方式。希望有所帮助。

Try it out. I have it working this way. Hope that helps.

这篇关于如何缓存on Rails的3红宝石查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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