Posted about 8 years ago. Visible to the public.

How to not die with ActionView::MissingTemplate when clients request weird formats

When HTTP clients make an request they can define which response formats they can process. They do it by adding a header to the HTTP request like this:

Accept: application/json

This means the client will only understand JSON responses.

When a Rails action is done, it will try to render a template for a format that the client understand. This means when all you are HTML templates, a request that only accepts application/json will raise an error:

An ActionView::MissingTemplate occurred in pages#foo: Missing template pages/foo, application/foo with {:locale=>[:de], :formats=>[:json], :handlers=>[:erb, :builder, :haml]}

This is because Rails tried to find a template like foo.js.erb but all it found was foo.html.haml (which the client doesn't understand).

Why does someone request my page with weird formats?

Stupidity. Anyway you cannot prevent people from making such requests.

What can I do to prevent this error?

You can choose not to care. Since e.g. making JSON requests for HTML services is not supported use of your page, you don't have to support them with a proper response.

If you really want to prevent ActionView::MissingTemplate you can write something like this in your controller action:

def foo respond_with do |format| format.html { render 'foo' } end # or shorter: respond_to :html end

Now JSON requests will get a 406 Not acceptable error, which is correct.

As an alternative you can also define your routes for certain formats only:

# routes.rb contraints(:format => /html/) do match 'foo' => 'pages#foo' end

Now JSON requests will get a 404 Not found error, which is slightly less correct than a 406, but will still serve your purpose.

makandra has been working exclusively with Ruby on Rails since 2007. Our laser focus on a single technology has made us a leader in this space.

Owner of this card:

Henning Koch
Last edit:
over 1 year ago
by Judith Roth
response, format, error, exception
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more