Caching in Rails 4

A Seemingly Important Caching Method, Undocumented

At the time of this writing, the Rails caching docs seem to be missing what I think is a necessary piece, low-level caching. I don’t get why that is. I imagine there must be some good reason and I just don’t know enough yet to understand what that reason is, but I want to talk about low-level caching here because I’ve found it useful.

Before We Start – Enable Caching In Dev

First of all, before you try any of the code I’m going to show here, make sure that in config/environments/development.rb you set perform_caching to true.

Fragment Caching: Totally Fucked Up?

I looked at the Rails caching docs for the first time in a long time today and I noticed that Page Caching and Action Caching seem to be deprecated. (And just as a heads up, Heroku doesn’t seem to have caught up with its Rails caching docs.)

The only kinds of caching that seem to be supported now in Rails 4 are Fragment Caching and SQL caching. The idea of fragment caching makes sense to me but the use cases seem totally fucked up:


It’s these parts that to me seem fucked up: Order.find_recent and Product.all. Aren’t you not supposed to do stuff like that in the view? Aren’t you supposed to do something more like @orders = Order.find_recent in the controller, and then <% @orders.each do %> in the view? Rules aside, I almost always set that kind of stuff in the controller as opposed to calling the model code directly in the view. So what the fuck? I’m seriously confused. I don’t really have an answer for this part of it. I’m just genuinely bamboozled.

Low-Level Caching

In the past I’ve used low-level caching and it’s been pretty great. Here’s how it might work. Let’s say you have a controller action that looks like this:

With low-level caching you can change the code to this:

And that works.