views:

61

answers:

2

How can I redirect a misspelled url to some default url in case a user mistypes a url?

+5  A: 

You can add a default root, catch all routes.

By example an extract from Typo source code :

map.connect '*from', :controller => 'articles', :action => 'redirect'

In your controller you have a params[:from] which an Array of all params of your URL

shingara
This looks great but I'm looking for a catch all. Any typo gets redirected to the root or some default url
Sam
Which it is. You can use the catch-all route to connect to a specific action, and inside the action you call `redirect_to`. Or you connect the catch-all directly to the action that you want the user to see.
averell
Also , remember to put it at the end of your route file :)
NM
+1  A: 

You can rescue ActionController::RoutingError from application_controller, like CanCan suggests for unauthorized access:

class ApplicationController < ActionController::Base

  (...)
  # Reditect to a default route when user inputs a wrong one
  rescue_from ActionController::RoutingError do |exception|
    flash[:error] = "There is no such route"
    redirect_to root_url
  end

end
Fer
(...) not quite sure what that means, but the method works
Sam
Rails uses that exception when route recognition fails.Here we stop that exception and take the user elsewhere instead of letting rails show the default route error message.You may find Mr Ryan Bates more illustrative than me: http://railscasts.com/episodes/53-handling-exceptions
Fer