Cat Gallagher Cat Gallagher - 2 years ago 346
Ruby Question

ActionView::MissingTemplate, Rails 5 API with JSON

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?


class Api::ThingController < ApplicationController
def thing
render json: {error: 'This is my error message.'}, status: 422


require 'test_helper'
class Api::ThingControllerTest < ActionDispatch::IntegrationTest
test "the truth" do
get '/api/thing'
assert_response 422

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,


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"

Answer Source

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'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download