treesky606
treesky606

Reputation: 40

How to deal with 404 error in Ruby on Rails?

How do I write the controller, routing, or view to present 404s when a routing error occurs?

For example,if the user access a url address

http://0.0.0.0:3000/posts/likes

The likes path isn't a method in the routing. How do I redirect it to 404 page?

Upvotes: 1

Views: 554

Answers (3)

bricker
bricker

Reputation: 8941

Rails allows you to define your own "exceptions app" to handle errors. This is one way to handle errors. In application.rb:

config.exceptions_app = self.routes

And then in your routes:

match '/404', to: 'errors#not_found'
match '/500', to: 'errors#error'

Then you just need an ErrorsController with methods for different errors you want to handle, and template files for each one, plus an errors.html.erb layout file if you want to use it.

ActionController::RoutingError and ActiveRecord::RecordNotFound automatically raise a 404 in production.

Upvotes: 2

Deal Way
Deal Way

Reputation: 36

1.In the application_controller.rb

# ..
rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found

private
def record_not_found(e)
  render ‘errors/not_found’, :status => 404
end

2.Create a errors folder and a file named not_found.html.erb

3.Add the source to application_controller.rb

def record_not_found(e)
  render ‘errors/not_found’, :status => 404, :layout => ‘error’
end

Upvotes: 2

Samiron
Samiron

Reputation: 5317

A quick googling gave few resources. I would suggest following two.

Though I didnt use any of these personally, I think the gem can help you robustly. And yes, second link came from a real life scenario.

Upvotes: 3

Related Questions