【发布时间】:2011-02-28 12:54:09
【问题描述】:
例如输入:localhost:3000/absurd-non-existing-route
如何在 Rails 中获取指向应用程序主页的无效路由?
【问题讨论】:
标签: ruby-on-rails redirect exception-handling routing routes
例如输入:localhost:3000/absurd-non-existing-route
如何在 Rails 中获取指向应用程序主页的无效路由?
【问题讨论】:
标签: ruby-on-rails redirect exception-handling routing routes
这是我试图找到一个通用的包罗万象的路由异常解决方案的方法。它处理最流行的内容类型。
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错误创建自己的视图。
【讨论】:
如果您使用的是 rails 3,
请使用以下解决方案
在您的routes.rb 中,在文件末尾添加以下行
匹配 "*path" => "controller_name#action_name",通过:[:get, :post]
在你的控制器中,添加
def action_name
redirect_to root_path
end
如果您使用的是 rails 4
在你的routes.rb写下这一行
match '*path' => redirect('/'), via: :get
【讨论】:
在 Rails 4+
上编辑您的routes.rb 文件,在用户@Rails: redirect all unknown routes to root_url 提到的最后一个end 上方添加get "*path", to: redirect('/') 行
【讨论】:
在你的ApplicationController 中使用rescue_from 来拯救ActionController::RoutingError 并在发生这种情况时重定向到主页。
目前这在 Rails 3 中不起作用。 A ticket has been filed.
【讨论】:
The solution presented here 效果很好
#Last route in routes.rb
match '*a', :to => 'errors#routing'
# errors_controller.rb
class ErrorsController < ApplicationController
def routing
render_404
end
end
【讨论】: