How to cache a query in Ruby on Rails 3

2019-03-11 13:36发布

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.

2条回答
淡お忘
2楼-- · 2019-03-11 13:39

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).

查看更多
来,给爷笑一个
3楼-- · 2019-03-11 13:42

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') }

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.

查看更多
登录 后发表回答