Rails render 404 not found from a controller action
Rails redirects route not found requests to 404.html page. Sometimes, we need to redirect to 404 not found page from a controller action. This can be done by rendering 404.html page or raising ActionController::RoutingError error.
Render 404.html page
Instead of using ActionController::RoutingError
,
404.html
page from the public
folder can directly be rendered.
This will render public/404.html
page and serve the purpose of rendering
not found page.
A method can be written in ApplicationController
as,
Render a custom 404 not found page
Instead of default public/404.html
page,
a custom html page can also be rendered with render
.
Example.
Raise ActionController::RoutingError
When we want to show page not found,
raise ActionController::RoutingError
error.
This can also be written as given below.
This can be added as a method on ApplicationController
Usage
This can be used in a controller action to render not found page.
Reference:
Subscribe to Ruby in Rails
Get the latest posts delivered right to your inbox