简体   繁体   中英

How to route all undefined actions to root_url in Rails?

I have 6 controllers currently, and not everyone has defined all 6 actions. I'm hoping to route all undefined actions to root_url so we don't have that ugly error message but can't figure out a way to do that. Can anyone help me out?

As others have pointed out in the comments, you probably do not actually want to do what you are asking, however, since you asked it, the solution you are looking for is a few lines added to your ApplicationController .

unless Rails.application.config.consider_all_requests_local
  rescue_from AbstractController::ActionNotFound, with: :handle_error
  rescue_from ActiveRecord::RecordNotFound, with: :handle_error
  rescue_from ActionController::RoutingError, with: :handle_error
  rescue_from ActionController::UnknownController, with: :handle_error
  rescue_from ActionController::UnknownAction, with: :handle_error
end

protected
def handle_error
  redirect_to root_url
end

This will basically catch all errors around missing routes, controllers, and actions and redirect to the root_url. Since it is in your ApplicationController, which all your other controllers derive from, it works for all of your missing things.

Please note that because I wrapped those rescues in that unless, you will still see the errors in your local dev which you want so that you can deal with any real problems.

Again, you are probably better off putting some custom pages around the different error types like 404, 500, etc and then either redirecting the user or letting them navigate themselves.

As of rails 3.2 you can even direct these errors to a specific rack end point (including the app itself) and deal with them however you want. This is much nicer than the solution above, but only works on rails 3.2 or later. For older versions the above solution will work.

To do this you would add this line to your application.rb

config.exceptions_app = self.routes

Then, in your routes file you can do things like this:

match '/404', to: "error_pages#handle_404"

That expects you to have an ErrorPages controller with a handle_404 action but you can also just route it to where ever, including your root_url, whatever that is. You can do this for all of the error codes.

在每个控制器的未定义操作中,只需编写:

redirect_to root_url

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM