Rails:如何防止与静态和动态页面发生路由冲突?

时间:2018-05-12 01:19:47

标签: ruby-on-rails ruby url routes name-collision

我有以下路线:

Rails.application.routes.draw do
  get '/:id', to: 'foo#bar', constraints: { id:  /\d+/ }
end

/ 1 加载我的记录,ID为#1。问题是我的路由与Rails默认静态页面(404,500等等)冲突。

如何使用动态路线工作的静态错误页面?

如果可能的话,我不介意将我的静态页面移动到例如 / errors / 404 之类的路径。

编辑1

重新打开ActionDispatch :: ShowExceptions类并更改私有方法render_exception是一个非常糟糕的解决方案:

配置/ application.rb中:

require_relative 'boot'

require 'rails/all'

Bundler.require(*Rails.groups)

module MyApp
  class Application < Rails::Application
    config.load_defaults 5.2
    config.exceptions_app = self.routes
  end
end

module ActionDispatch
  class ShowExceptions
    private
      def render_exception(request, exception)
        backtrace_cleaner = request.get_header "action_dispatch.backtrace_cleaner"
        wrapper = ExceptionWrapper.new(backtrace_cleaner, exception)
        status  = wrapper.status_code
        request.set_header "action_dispatch.exception", wrapper.exception
        request.set_header "action_dispatch.original_path", request.path_info
        request.path_info = "/errors/#{status}"
        response = @exceptions_app.call(request.env)
        response[1]["X-Cascade"] == "pass" ? pass_response(status) : response
      rescue Exception => failsafe_error
        $stderr.puts "Error during failsafe response: #{failsafe_error}\n  #{failsafe_error.backtrace * "\n  "}"
        FAILSAFE_RESPONSE
      end
  end
end

我已将request.path_info = "/#{status}"更改为request.path_info = "/errors/#{status}"

我根本不喜欢这个解决方案。

0 个答案:

没有答案