【发布时间】:2026-02-12 09:35:01
【问题描述】:
尝试在我的 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=>[: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
【问题讨论】:
-
也许尝试在您以 JSON 形式返回的哈希上调用
to_json? -
试试
format.json { render json: ... } -
上述两种方法都试过了,都不管用。不过谢谢!
标签: ruby-on-rails ruby json api ruby-on-rails-5