Ruby on rails 将所有路由错误重定向到应用程序的根URL
例如,键入:Ruby on rails 将所有路由错误重定向到应用程序的根URL,ruby-on-rails,redirect,exception-handling,routing,routes,Ruby On Rails,Redirect,Exception Handling,Routing,Routes,例如,键入:localhost:3000/不存在的路由 如何获取指向Rails中应用程序主页的无效路由?在ApplicationController中使用,以拯救ActionController::RoutingError,并在发生错误时重定向到主页 这在Rails 3中目前不起作用 效果很好 #Last route in routes.rb match '*a', :to => 'errors#routing' # errors_controller.rb class ErrorsCo
localhost:3000/不存在的路由
如何获取指向Rails中应用程序主页的无效路由?在ApplicationController
中使用,以拯救ActionController::RoutingError
,并在发生错误时重定向到主页
这在Rails 3中目前不起作用 效果很好
#Last route in routes.rb
match '*a', :to => 'errors#routing'
# errors_controller.rb
class ErrorsController < ApplicationController
def routing
render_404
end
end
#routes.rb中的最后一条路线
匹配'*a',:to=>'错误#路由'
#错误\u controller.rb
类错误控制器<应用程序控制器
def路由
渲染404
结束
结束
Rails 4上的+
编辑您的routes.rb
文件,方法是添加一个get“*path”,以:重定向(“/”)
行,就在用户提到的最后一个end
上方,如果您使用的是rails 3
,
使用以下解决方案
在routes.rb
中,在文件末尾添加以下行
匹配“*路径”=>“控制器名称#操作名称”,通过:[:获取,:发布]
在控制器中,添加
def action_name
redirect_to root_path
end
如果您使用的是rails 4
在你的routes.rb中写这行
match '*path' => redirect('/'), via: :get
下面是我为寻找路由异常的通用解决方案而想到的一些东西。它处理最流行的内容类型
routes.rb
错误控制器
类错误控制器
ErrorsController
设计得更通用,可以处理各种错误
建议在app/views/errors/404.html
中为404错误创建自己的视图
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