How to cache Rails API actions

477 Views Asked by At

What is the best and correct approach to do caching for actions?

  • Am I forced to ActionController::Base?
  • Is there another way (keeping ActionController::API present)?
  • Do I have to push caching down to Model layer?

I saw that Rails 6 (maybe prior) does not support action caching out of the box anymore. The caching was extracted to a gem: actionpack-action_caching https://github.com/rails/actionpack-action_caching. I installed it, but it seems not working with ActionController::API, it only works with ActionController::Base.

class ApplicationController < ActionController::API

must be changed to

class ApplicationController < ActionController::Base

Then, and only then I can cache an action like so:

    class CategoryController < ApplicationController
      caches_action :index
      def index
        @root_categories = Category.roots
      end
    end

Thank you in advance

1

There are 1 best solutions below

0
Cameron On

The gem adds these methods to your controllers by including ActionController::Caching in ActionController::Base (see here). To add this behaviour to controllers that don't extend from ActionController::Base, simply include ActionController::Caching.

e.g.

class ApplicationController < ActionController::API
  include ActionController::Caching
end