Rails routing: Using constraints to avoid "Missing template" errors

Updated . Posted . Visible to the public.

You can use constraints in your routes.rb to avoid getting ActionView::MissingTemplate errors when wrong routes are called. Instead, the user will see a 404.

If you want multiple routes to use the same constraint you can use the block syntax:

constraints(format: 'html') do
  resources :pages
  resources :images
end

If you want constraints only on certain routes, you can do:

get '/users/account' => 'users#account', constraints: { format: 'html' }

Tip

You can also avoid this error type through format constraints in your controllers and use correct file names.

Judith Roth
Last edit
Emanuel
License
Source code in this card is licensed under the MIT License.
Posted by Judith Roth to makandra dev (2019-10-08 08:23)