Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/54.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 将所有路由错误重定向到应用程序的根URL_Ruby On Rails_Redirect_Exception Handling_Routing_Routes - Fatal编程技术网

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