将所有路由错误重定向到应用程序的根URL

fen*_*nec 8 redirect routing routes exception-handling ruby-on-rails

例如输入:localhost:3000/absurd-non-existing-route 如何在Rails中获取指向应用程序主页的无效路由?

Boo*_*age 6

这里介绍的解决方案效果很好

#Last route in routes.rb
match '*a', :to => 'errors#routing'

# errors_controller.rb
class ErrorsController < ApplicationController
  def routing
    render_404
  end
end
Run Code Online (Sandbox Code Playgroud)


Epi*_*ene 6

Rails 4 +上

如user @ Rails所述,通过在最后一行上方routes.rb添加get "*path", to: redirect('/')一行来编辑文件:将所有未知路由重定向到root_urlend


x1a*_*1a4 3

在您的救援中使用rescue_fromApplicationController来救援ActionController::RoutingError并在发生情况时重定向到主页。

目前这在 Rails 3 中不起作用。票证已提交。