ActionView::MissingTemplate、Rails 5 API 和 JSON
ActionView::MissingTemplate, Rails 5 API with JSON
在我的 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
完整错误信息:
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
这与 an issue in Rails 5 beta ActionController::API and Jbuilder. It looks like it has been fixed by this pull request 有关。
同时您可以 return 纯文本并设置内容类型,如下所示:
render plain: {error: 'This is my error message.'}.to_json, status: 422, content_type: 'application/json'
在我的 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
完整错误信息:
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
这与 an issue in Rails 5 beta ActionController::API and Jbuilder. It looks like it has been fixed by this pull request 有关。
同时您可以 return 纯文本并设置内容类型,如下所示:
render plain: {error: 'This is my error message.'}.to_json, status: 422, content_type: 'application/json'