Cat Gallagher
Cat Gallagher

Reputation: 107

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?

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

Upvotes: 6

Views: 4751

Answers (1)

Ryenski
Ryenski

Reputation: 9692

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'

Upvotes: 5

Related Questions