Search code examples
ruby-on-railscachingruby-on-rails-6action-caching

How to expire Action Cache when underlying model is updated in Rails 6?


I am using Action Caching which seems to work OK with Rails 6.

The issue is how to expire the cache when the underlying model is updated?

According to Rails Guides

See the actionpack-action_caching gem. See DHH's key-based cache expiration overview for the newly-preferred method.

According to the Action Caching gem issue, using a Rails Observer to sweep the cache would work.

https://github.com/rails/rails-observers#action-controller-sweeper

But Rails Observer does not seem to work with Rails 6.

So, how to expire the cache with an after_save callback?


Solution

  • You can pass in your own cache_path to expire the key. You still need to fetch some record to calculate it though.

    class MyController < ApplicationController
      before_action :set_record
    
      caches_action :show, expires_in: 1.hour, cache_path: ->(_) { show_cache_key }
    
      def show; end
    
      private
    
      def set_record
        @record = Record.find(params[:id])
      end
    
      def show_cache_key
        @record.cache_key
      end
    end
    

    Doing cache invalidation by hand is an incredibly frustrating and error-prone process so I would avoid invalidating keys in an after_step and use key based expiration instead.