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.
render :file => "#{Rails.root}/public/404.html", layout: false, status: :not_found
# Older versions of Rails use RAILS_ROOT constantThis will render public/404.html page and serve the purpose of rendering
not found page.
A method can be written in ApplicationController as,
def render_not_found
render :file => "#{RAILS_ROOT}/public/404.html", :status => 404
endRender a custom 404 not found page
Instead of default public/404.html page,
a custom html page can also be rendered with render.
Example.
render :file => "#{Rails.root}/path/to/file.html", layout: false, status: :not_found
# Older versions of Rails use RAILS_ROOT constantRaise ActionController::RoutingError
When we want to show page not found,
raise ActionController::RoutingError error.
raise ActionController::RoutingError.new('Not Found')This can also be written as given below.
raise ActionController::RoutingError, 'Not Found'This can be added as a method on ApplicationController
def not_found
raise ActionController::RoutingError.new('Not Found')
endUsage
This can be used in a controller action to render not found page.
def show
return not_found if some_condition
endReference:
Subscribe to Ruby in Rails
Get the latest posts delivered right to your inbox