How do you cache collections in Rails

If you want to speed up your Rails website you've probably heard of caching.
When talking about caching people always tell you to make sure you invalidate
the cache at the right time. Otherwise you risk displaying old content.
So when is the right time to invalidate a cache for a collection of objects in
Rails? What do you do if only one object changes? Is it really worth it to do
this?

The answer is 'yes'. It is almost always worth doing it.
Cache invalidation should be done by choosing the correct cache key. If you have a collection of ActiveRecord objects a nice approach could look like this.

edit: Thanks to pcreux for pointing out an improvement in the comments.

articles = BlogArticles.active # or any other collection
cache_key = [“blog-articles”, articles.pluck(:id), articles.maximum(:updated_at)]

@cached_articles = Rails.cache.fetch(cache_key) do
  # This is run if the cache is empty, e.g. on a new cache_key
  # Fetch you articles here.
end

# continue with your cached articles

Thanks for reading and don't miss my next post. Enter your email in the box at
the top of the page.