【问题标题】:ActionView::MissingTemplate, Rails 5 API with JSONActionView::MissingTemplate,带有 JSON 的 Rails 5 API
【发布时间】: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


【解决方案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'

【讨论】:

  • 谢谢,这很有帮助。