Using the 404 for Missing Routes and Actions


#1

I’ve tried searching the list for this but I’m not really sure what
Rails would call it. Basically what I’m wanting to do is to help
against users changing the URL string, or to help users with expired
bookmarks from the previous version of the site. When a method
doesn’t exist or an action on a method rather then showing “Routing
Error” or “Unknown Action” I want to be able to either forward that to
the 404 error page or just redirect it to my home controller’s index
action. How would one go about doing this?

Regards,

Tim


#2

There may be a more elegant way, but this works:

Create a controller with an action that returns a 404 (or an action
that would redirect to your home page whatever that is or whatever
else you want to happen)

class ErrorsController < ApplicationController
def not_found
render :file => “#{RAILS_ROOT}/public/404.html”, :layout =>
false, :status => 404
end
end

then put a catch-all route to this at the end of /config/routes.rb:

ActionController::Routing::Routes.draw do |map|

snip

map.connect ‘*path’, :controller => ‘errors’, :action => ‘not_found’
end

Any input that a miscreant user enters that doesn’t match a route will
be caught by this final route and cause the not_found action to fire.


#3

On 7/29/07, blaine removed_email_address@domain.invalid wrote:

I’ve tried searching the list for this but I’m not really sure what
Rails would call it. Basically what I’m wanting to do is to help
against users changing the URL string, or to help users with expired
bookmarks from the previous version of the site. When a method
doesn’t exist or an action on a method rather then showing “Routing
Error” or “Unknown Action” I want to be able to either forward that to
the 404 error page or just redirect it to my home controller’s index
action. How would one go about doing this?

Those development stack traces are only shown in development mode, or
in production mode IF the request is from the local web server. Look
at extending #rescue_action_in_public to suit your needs:

http://dev.rubyonrails.org/browser/branches/1-2-stable/actionpack/lib/action_controller/rescue.rb#L50

I don’t know if there are any decent tutorials written on it though.
But if there aren’t, they should be written for edge which improves
this a lot IMO:

http://dev.rubyonrails.org/browser/trunk/actionpack/lib/action_controller/rescue.rb#L90

You can easily define a status code and rendered template for custom
exceptions without overwriting the method.


Rick O.
http://lighthouseapp.com
http://weblog.techno-weenie.net
http://mephistoblog.com