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
2010-06-30 07:54:38
This looks great but I'm looking for a catch all. Any typo gets redirected to the root or some default url
Sam
2010-06-30 08:32:21
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
2010-06-30 09:50:24
Also , remember to put it at the end of your route file :)
NM
2010-06-30 10:46:39
+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
2010-06-30 14:58:39
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
2010-07-02 12:23:46