“iOS 14 will let you change your default email and web browser apps”

“The Looming Bank Collapse”

“…Just Wear a Face Mask!”

“A More Perfect Union”

Rails Page Caching Not Invalidating Root Index Page

This site runs on a Rails app, and I realized while working on it that I had not enabled page caching for the index and post pages, as I had intended. When I went to add the page caches, I realized that the index page cache wasn’t being invalidated correctly when I made a new post, despite my explicit invalidation of the cache.

My posts_controller.rb (quite a bit omitted for clarity):

class PostsController < ApplicationController

  caches_page :index, :show

  def create
    @post = Post.new(post_params)

    respond_to do |format|
      if @post.save
        expire_page action: :index
        expire_page action: :show, id: @post.slug
        format.html { redirect_to @post, notice: 'Post was successfully created.' }
        format.json { render :show, status: :created, location: @post }
        format.html { render :new }
        format.json { render json: @post.errors, status: :unprocessable_entity }

Note the expire_page calls. I have a default route set to send the root to posts#index, and was correctly getting an index.html page cache generated. When I created a new post, I noticed that the index page wasn’t being deleted.

The key is in the expire_page method, which looks like this:

def cache_page(content, path, extension = nil, gzip = Zlib::BEST_COMPRESSION)
  if perform_caching
    page_cache.cache(content, path, extension, gzip)

It takes a path as its second parameter, which is used as the key for the cached page, while it’s created with an action, and I had to manually invalidate the cache for my root route, “/”. I added:

expire_page '/'

and it all worked correctly. I hope this helps someone else down the road, since it didn’t turn up when I was googling it earlier today.