Redirect All Routing Errors to Root URL of the Application
For example typing: localhost:3000/absurd-non-existing-route
H开发者_如何学Goow do I get invalid routes to point to the main page of the application in Rails?
The solution presented here works pretty well
#Last route in routes.rb
match '*a', :to => 'errors#routing'
# errors_controller.rb
class ErrorsController < ApplicationController
def routing
render_404
end
end
On Rails 4+
Edit your routes.rb
file by adding a get "*path", to: redirect('/')
line just above the last end
as mentioned by user @ Rails: redirect all unknown routes to root_url
Use rescue_from in your ApplicationController
to rescue ActionController::RoutingError
and redirect to the home page when it happens.
This will not work in Rails 3 currently. A ticket has been filed.
If you are using rails 3,
Use the following solution
In your routes.rb
, add the following line in the end of the file
match "*path" => "controller_name#action_name", via: [:get, :post]
And in your Controller, add
def action_name
redirect_to root_path
end
If you are using rails 4
Write this line in your routes.rb
match '*path' => redirect('/'), via: :get
Here's something I came up with trying to find a universal catch-all solution for routing exceptions. It handles most popular content types.
routes.rb
get '*unmatched_route', to: 'errors#show', code: 404
ErrorsController
class ErrorsController < ApplicationController
layout false
# skipping CSRF protection is required here to be able to handle requests for js files
skip_before_action :verify_authenticity_token
respond_to :html, :js, :css, :json, :text
def show
respond_to do |format|
format.html { render code.to_s, status: code }
format.js { head code }
format.css { head code }
format.json { render json: Hash[error: code.to_s], status: code }
format.text { render text: "Error: #{ code }", status: code }
end
end
private
def code
params[:code]
end
end
The ErrorsController
is designed to be more universal, to handle all kind of errors.
It is advised to create your own view for the 404 error in app/views/errors/404.html
.
精彩评论