Rails:控制器操作导致 "missing a template for this request format and variant" 错误后呈现 JSON

Rails: Render JSON after Controller action results in "missing a template for this request format and variant" error

我有这个简单的管理控制器,我试图在调用 #reset 操作后显示一条消息,以便在操作完成时向管理员提供反馈(因为它执行 de seed.rb 文件)

该操作执行得很好,但我无法让它显示 msg 并且我在服务器日志中收到此消息:

ActionController::UnknownFormat (Api::V1::AdminController#reset is missing a template for this request format and variant.

request.formats: ["application/json"]
request.variant: []):


class Api::V1::AdminController < Api::V1::BaseController
  before_action :initialize

  def seed
    @builder.process_file
  end

  def reset
    Rails.application.load_seed do
      msg = { :status => "ok" }
      respond_to do |format|
           format.json  { render :json => msg }
         end
    end
  end

  private

  def initialize
    @builder = PaymentBuilder.new
  end
end

我做错了什么?

编辑:

我必须在控制器的 class 级别声明 respond_to :json 并将操作块更改为

  def reset
    Rails.application.load_seed
    msg = { :reset => "OK" }
      respond_with do |format|
        format.json  { render :json => msg }
      end
  end

现在可以正常渲染了。

我猜这是因为你在块内部渲染,我认为你不能那样做