例如输入:
localhost:3000/absurd-non-existing-route
如何获取指向 Rails 中应用程序主页的无效路由?
在Rails 4+
编辑您的
routes.rb
文件,在最后一个 get "*path", to: redirect('/')
上方添加 end
行,如用户 @ Rails 所提到的:将所有未知路由重定向到 root_url
此处介绍的解决方案效果很好
#Last route in routes.rb
match '*a', :to => 'errors#routing'
# errors_controller.rb
class ErrorsController < ApplicationController
def routing
render_404
end
end
使用 ApplicationController
中的
rescue_from来救援
ActionController::RoutingError
并在发生情况时重定向到主页。
目前这在 Rails 3 中不起作用。 已提交罚单。
这是我想出的一些东西,试图找到一个通用的包罗万象的路由异常解决方案。它可以处理最流行的内容类型。
config.exceptions_app = routes
match '/404', to: 'errors#show', via: :all, code: 404
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
ErrorsController
的设计更加通用,可以处理各种错误。
建议在
app/views/errors/404.html
中创建自己的404错误视图。
如果您使用的是 Rails 3,
使用以下解决方案
在您的
routes.rb
中,在文件末尾添加以下行
匹配“*path”=>“controller_name#action_name”,通过:[:get, :post]
并在您的控制器中添加
def action_name
redirect_to root_path
end
如果您使用导轨4
将此行写在您的
routes.rb
中
match '*path' => redirect('/'), via: :get