使用 JBuilder 和 Rails 6 进行片段缓存时未定义方法 'perform_caching'

Undefined method 'perform_caching' when doing fragment caching with JBuilder and Rails 6

我正在尝试将片段缓存应用于我的一个 jbuilder 视图:

# frozen_string_literal: true

json.cache!(['1', @countries], expires_in: 60.minutes) do
  json.partial!('country', collection: @countries, as: :country)
end

不幸的是,这会输出以下错误:

ActionView::Template::Error (undefined method `perform_caching' for #<Api::CountriesController:0x00005572a6187f90>):
  1: # frozen_string_literal: true
  2: 
  3: json.cache!(['1', @countries], expires_in: 60.minutes) do
  4:   json.partial!('country', collection: @countries, as: :country)
  5: end

我已将以下宝石添加到我的 Gemfile

gem "actionpack-page_caching", "~> 1.2"
gem "actionpack-action_caching", "~> 1.2"

在我的 application.rb 中,我添加了以下几行:

config.action_controller.perform_caching = true
config.cache_store = :memory_store, { size: 64.megabytes }

在 jbuilder 视图中启用片段缓存还需要什么?

我正在使用 Rails 6.0.2 和 jbuilder 2.7。

我认为您需要将 ActionController::Caching 添加到您的基本控制器 ApplicationController 中,因为它未包含在 ActionController::API

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

或者,如果您希望仅在此控制器中使用缓存,则可以仅将其包含在 Api::CountriesController

https://github.com/rails/jbuilder/issues/331

我也相信你不需要额外的宝石

gem "actionpack-page_caching", "~> 1.2"
gem "actionpack-action_caching", "~> 1.2"