Reputation: 3
I'm relatively new to Rails, and I still don't know a lot about routing. How would I display a certain view (such as 404.html.erb
) when the user gets a certain error code (404)? For example, if a user GETs a page that doesn't exist (404), how can I listen for that and display a certain page on that event?
I know that a Rails app comes with a public
folder and pre-generated 404, 500, and 422 error code .html pages, but they don't seem to work for me. When I go to a page that doesn't exist, I receive a GET error. How would I change this?
Thanks!
Upvotes: 0
Views: 440
Reputation: 3603
You can setup custom routes to render dynamic pages from your controller just as normal controller-view templates.
config/routes.rb
MyApp::Application.routes.draw do
# custom error routes
match '/404' => 'errors#not_found', :via => :all
match '/500' => 'errors#internal_error', :via => :all
end
app/controllers/errors_controller.rb
class ErrorsController < ApplicationController
def not_found
render(:status => 404)
end
end
app/views/errors/not_found.html.erb
<div class="container">
<div class="align-center">
<h3>Page not found</h3>
<%= link_to "Go to homepage", root_path %>
</div>
</div>
Upvotes: 1
Reputation: 1254
You can do as below:
# in config/application.rb
config.exceptions_app = self.routes
# For testing on development environment, need to change consider_all_requests_local
# in config/development.rb
config.consider_all_requests_local = false
Restart server after those changes.
# in routes.rb
get '/404', to: 'errors#not-found'
get '/422', to: 'errors#unprocessable-entity'
get '/500', to: 'errors#internal-error'
Upvotes: 1
Reputation: 369
You can access the public pages through the localhost. Rails automatically uses those pages when it encounters that error or 404 on production.
localhost:3000/404 # => renders the 404.html
localhost:3000/500 # => renders the 500.html
Upvotes: 0