I am consistently getting an ActionView::MissingTemplate error when trying to render JSON in my Rails 5 Api. I just want to render the pure JSON, without a jbuilder or other view. Can anyone help?
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
full error message:
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
This is related to an issue in Rails 5 beta ActionController::API and Jbuilder. It looks like it has been fixed by this pull request.
Meantime you can return plain text and set the content type, like so:
render plain: {error: 'This is my error message.'}.to_json, status: 422, content_type: 'application/json'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With