shems eddine
shems eddine

Reputation: 49

Rails cache ActiveRecord result

My current homepage displays all available categories and all of the number of posts each category has. This of course is having a performance hit on the website and i was just wondering if this could be cached at all?

I don't mind if the cache is a little out of date and if the number of posts isn't 100% accurate at every refresh, but i would like it to only make the query every 30 minutes or so.

Upvotes: 5

Views: 2248

Answers (2)

Ruby Racer
Ruby Racer

Reputation: 5740

In Rails you can cache pretty much everything.

You can cache partials or queries. And you can expire them manually too.

For example

cache('categorylist') do
     render partial: 'such'
end

And in the post.rb model, after each create of post, reset this and force it to evaluate on next run

after_create {
    Rails.cache.delete('categorylist')
}

This way, your partial will only be evaluated (and written to cache) when a new post has been created. All other times, it will be fetched from cache.

Upvotes: 2

Adam Berman
Adam Berman

Reputation: 794

ActiveRecord caches queries so that they don't have to be re-executed. However, this sort of caching does not persist between requests. View caching may work better for you - I'd look into Fragment Caching, the rails docs for which can be found here: http://edgeguides.rubyonrails.org/caching_with_rails.html

The crux though is that as you can cache objects as you render them like this (from the doc mentioned above):

<% @products.each do |product| %>
  <% cache product do %>
    <%= render product %>
  <% end %>
<% end %>

This writes each product to a key/value store. It records the updated_at timestamp for the data so that you don't serve stale data.

Using the format from the above example, you could store the html listing the categories and posts per category in the cache.

Upvotes: 0

Related Questions