Search code examples
ruby-on-railsrubyactionviewmissing-template

ActionView::MissingTemplate ----- Missing template messages/show


I have the following errors_controller.rb

class ErrorsController < ActionController::Base
layout 'bare'

def show
return render_error params[:id], :ok
end

def index
  request.format.to_s.downcase == 'application/json' ? json_error : html_error
  return
end

private

def exception
  env['action_dispatch.exception']
end

def html_error
  if exception.nil?
    render_error 404
  else
    render_error 500
  end
end

def json_error
  if exception.nil?
    render json: error_hash(:resource_not_found), status: 404
  else
    render json: error_hash(:internal_server_error), status: 500
  end
end

def error_hash(code)
  {
    errors: [
      {
        message: I18n.t("errors.api.#{code}"),
        code: code
      }
    ]
  }
end

def render_error(code, status_type = nil)
  @error = ErrorMessage.new(code, status_type)
  render @error.partial, status: @error.status
end
end

When a request is made to /api/test.xml It gives me

ActionView::MissingTemplate at /api/test.xml
Missing template messages/show with {:locale=>[:en], :formats=>[:xml],       :handlers=>[:erb, :builder, :raw, :ruby, :haml]}

I dont want to do

rescue_from(ActionController::MissingTemplate)

As this will handle all the action missing template errors, even if there are some spelling errors in the url.

I want a wholesome approach to throw a 404 for any request (.xml,.jpeg,.....)

Attempts

I tried adding a before_filter still gives me the same error.

I added config.action_dispatch.ignore_accept_header = true in application.rb, still no luck.

Can anyone show me some direction with this? Thank you in advance


Solution

  • You can do:

    def render_error(code, status_type = nil)
      @error = ErrorMessage.new(code, status_type)
      respond_to do |format|
        format.any(:html, :json) { render @error.partial, status: @error.status }
        format.any { head 404, "content_type" => 'text/plain' }
      end
    end