How to cache a request in Ruby on Rails 3

I have the following query in my application

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

This request is loaded into each page view, as the categories are displayed on each page. This seems dirty to me, as the list of categories is often not updated. Is there a great way to cache request only? I tried

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

but I still see that the request is loaded every time from the database in the development log.

+8
caching activerecord ruby-on-rails-3
source share
2 answers

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 be read only to make sure that the following categories of data are cached and have not expired. If it expires after 24 hours, it will query the model and write a new entry to the Rails cache.

For more information, I have followed the following guide .

Give it a try. It works for me like that. Hope this helps.

+18
source share

You can use fragment caching for the part of your presentation template that displays categories. This means that categories will be served from the cache repository and the request will be executed only once before the cache expires (using the expire_fragment method).

+4
source share

All Articles