【问题标题】:Redirect All Routing Errors to Root URL of the Application将所有路由错误重定向到应用程序的根 URL
【发布时间】:2011-02-28 12:54:09
【问题描述】:

例如输入:localhost:3000/absurd-non-existing-route 如何在 Rails 中获取指向应用程序主页的无效路由?

【问题讨论】:

    标签: ruby-on-rails redirect exception-handling routing routes


    【解决方案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错误创建自己的视图。

    【讨论】:

      【解决方案2】:

      如果您使用的是 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
      

      【讨论】:

        【解决方案3】:

        Rails 4+

        编辑您的routes.rb 文件,在用户@Rails: redirect all unknown routes to root_url 提到的最后一个end 上方添加get "*path", to: redirect('/')

        【讨论】:

          【解决方案4】:

          在你的ApplicationController 中使用rescue_from 来拯救ActionController::RoutingError 并在发生这种情况时重定向到主页。

          目前这在 Rails 3 中不起作用。 A ticket has been filed.

          【讨论】:

            【解决方案5】:

            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
            

            【讨论】:

              猜你喜欢
              • 2020-09-05
              • 1970-01-01
              • 1970-01-01
              • 2021-11-06
              • 1970-01-01
              • 2018-08-13
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多