如何在 Ruby on Rails 3 中缓存查询
我的应用程序中有以下查询
@categories = Category.joins(:posts).select('distinct categories.*').order('label')
由于类别显示在每个页面上,因此该查询会加载到每个页面视图上。这对我来说似乎很混乱,因为类别列表没有经常更新。有没有一种巧妙的方法来缓存查询?我已经尝试过
Category.cache do
@categories = Category.joins(:posts).select('distinct categories.*').order('label')
end
,但我仍然看到每次从开发日志中的数据库加载查询。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在您的控制器中,您可以尝试类似的操作:
它将仅读取以下数据块“类别”是否已缓存且未过期。如果 24 小时后过期,则会查询模型并将新记录写入 Rails 缓存。
有关更多信息,我遵循以下指南。
尝试一下。我就是这样工作的希望有帮助。
In your controller, you can try something like:
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.
您可以对视图模板中显示类别的部分使用片段缓存。这意味着类别将从缓存存储中提供,并且查询只会执行一次,直到缓存过期(通过使用
expire_fragment
方法)。You can use fragment caching for the part of your view template that displays the categories. This means that the categories will be served from the cache store and the query will only be executed once until the cache is expired (by using the
expire_fragment
method).