Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 886
shems eddine Avatar asked Oct 30 '22 15:10

shems eddine


1 Answers

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.

like image 68
Ruby Racer Avatar answered Nov 15 '22 05:11

Ruby Racer