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

时间:2016-04-26 16:36:45

标签: ruby-on-rails ruby json api 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

thing_controller_test.rb:

require 'test_helper'
class Api::ThingControllerTest < ActionDispatch::IntegrationTest
  test "the truth" do
    get '/api/thing'
    assert_response 422
  end
end

完整的错误消息:

  

错误:Api :: ThingControllerTest#test_the_truth:   ActionView :: MissingTemplate:缺少模板api / thing / thing,   应用程序/事物{:locale =&gt; [:en],:formats =&gt; [:json],   :variants =&gt; [],:handlers =&gt; [: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

1 个答案:

答案 0 :(得分:3)

这与Rails 5 beta ActionController :: API和Jbuilder中的an issue有关。它似乎已被pull request修复。

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

render plain: {error: 'This is my error message.'}.to_json, status: 422, content_type: 'application/json'