例如输入:
localhost:3000/absurd-non-existing-route
,如何使Rails应用程序把无效路由指向主页?localhost:3000/absurd-non-existing-route
,如何使Rails应用程序把无效路由指向主页?routes.rb
文件中添加get "*path", to: redirect('/')
行,将其放置在最后一个end
上方,即可按照用户@ Rails:将所有未知路由重定向到root_url的建议,将所有未知路由重定向到根URL。请注意保留HTML标记。这里介绍的解决方案非常有效
#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中无法实现。已提交工单。
在您的routes.rb
文件中,在文件末尾添加以下行:
match "*path" => "controller_name#action_name", via: [:get, :post]
And in your Controller, add
def action_name
redirect_to root_path
end
write this line in your routes.rb
match '*path' => redirect('/'), via: :get
这是我尝试寻找通用的解决方案以处理路由异常时想出来的东西。它处理了大多数流行的内容类型。
get '*unmatched_route', to: 'errors#show', 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错误视图。