ActionView::MissingTemplate,带有 JSON 的 Rails 5 API

Cat*_*her 6 ruby api json ruby-on-rails ruby-on-rails-5

尝试在我的 Rails 5 Api 中呈现 JSON 时,我一直收到 ActionView::MissingTemplate 错误。我只想呈现纯 JSON,没有 jbuilder 或其他视图。任何人都可以帮忙吗?

thing_controller.rb:

class Api::ThingController < ApplicationController
  def thing
    render json: {error: 'This is my error message.'}, status: 422
  end
end
Run Code Online (Sandbox Code Playgroud)

thing_controller_test.rb:

require 'test_helper'
class Api::ThingControllerTest < ActionDispatch::IntegrationTest
  test "the truth" do
    get '/api/thing'
    assert_response 422
  end
end
Run Code Online (Sandbox Code Playgroud)

完整的错误信息:

错误:Api::ThingControllerTest#test_the_truth:ActionView::MissingTemplate:缺少模板api/thing/thing,应用程序/thing with {:locale=>[:en], :formats=>[:json], :variants=>[ ], :handlers=>[:raw, :erb, :html, :builder, :ruby, :jbuilder]}。

application_controller.rb:

 class ApplicationController < ActionController::API
    include ActionController::Caching
    include ActionController::ImplicitRender  # want implicit view rendering for JBuilder

  before_action :add_cors_headers


  def options
    head(:ok) if request.request_method == "OPTIONS"
  end
Run Code Online (Sandbox Code Playgroud)

Boo*_*age 5

这涉及到一个问题,在Rails的5测试版的ActionController :: API和JBuilder。看起来它已经被这个pull request修复了。

同时,您可以返回纯文本并设置内容类型,如下所示:

render plain: {error: 'This is my error message.'}.to_json, status: 422, content_type: 'application/json'
Run Code Online (Sandbox Code Playgroud)