将所有路由错误重定向到应用程序的根URL

8
例如输入: localhost:3000/absurd-non-existing-route,如何使Rails应用程序把无效路由指向主页?
5个回答

7
在Rails 4及以上版本中,通过在routes.rb文件中添加get "*path", to: redirect('/')行,将其放置在最后一个end上方,即可按照用户@ Rails:将所有未知路由重定向到root_url的建议,将所有未知路由重定向到根URL。请注意保留HTML标记。

6

这里介绍的解决方案非常有效

#Last route in routes.rb
match '*a', :to => 'errors#routing'

# errors_controller.rb
class ErrorsController < ApplicationController
  def routing
    render_404
  end
end

3

在您的ApplicationController中使用rescue_from来拯救ActionController::RoutingError,并在发生时重定向到主页。

目前这在Rails 3中无法实现。已提交工单。


1
如果您正在使用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

如果您正在使用Rails 4,请在您的routes.rb文件中添加以下代码:

write this line in your routes.rb

match '*path' => redirect('/'), via: :get

1

这是我尝试寻找通用的解决方案以处理路由异常时想出来的东西。它处理了大多数流行的内容类型。

routes.rb

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错误视图。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接