2016-04-26 81 views
1

當我試圖在Rails 5 Api中呈現JSON時,我始終得到一個ActionView :: MissingTemplate錯誤。我只想呈現純JSON,沒有jbuilder或其他視圖。誰能幫忙?ActionView :: MissingTemplate,帶有JSON的Rails 5 API

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 

充滿錯誤消息:

Error: Api::ThingControllerTest#test_the_truth: ActionView::MissingTemplate: Missing template api/thing/thing, application/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 
+0

也許嘗試調用'上,你回來的JSON哈希to_json'? –

+0

嘗試'format.json {render json:...}' –

+0

嘗試了上述兩種方法,都沒有成功。謝謝你! –

回答

1

這與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' 
+0

謝謝,這是非常有幫助的。 – Jake

相關問題