我们刚刚将我们的应用程序升级到 Rails 3.2.2,现在遇到了处理错误的路由问题。
根据 José Valim's blog post ,我们添加了以下内容:
config.exceptions_app = self.routes
到 config/application.rb
匹配 "/404", :to => "errors#not_found"
到 config/routes.rb
(以及适当的 Controller / View )。
问题是我们需要 ourdomain.com/id
来显示 id
产品类别的索引页。
所以,现在 ourdomain.com/404
显示我们的 404 页面,而它应该显示 id
为 404 的类别的类别列表页面。
我们如何解决这个问题?
有没有办法让应用程序在每个错误被 routes
评估之前在每个错误前加上 error_
?
或者,可能以某种方式设置 config.exceptions_app
以引用 routes
文件中的命名空间?
或者,我可以创建第二个路由集并设置 config.exceptions_app = self.second_set_of_routes
吗?
谢谢!
最佳答案
我们遇到了同样的问题——错误代码与根级别的资源 ID 冲突(例如,ourdomain.com/:resource_id
和 ourdomain.com/404之间的冲突)
).
我们通过添加仅在处理异常时应用的路由约束来修改 José Valim 的解决方案:
# Are we handling an exception?
class ExceptionAppConstraint
def self.matches?(request)
request.env["action_dispatch.exception"].present?
end
end
MyApp::Application.routes.draw do
# These routes are only considered when there is an exception
constraints(ExceptionAppConstraint) do
match "/404", :to => "errors#not_found"
match "/500", :to => "errors#internal_server_error"
# Any other status code
match '*a', :to => "errors#unknown"
end
...
# other routes, including 'match "/:resource_id"'
end
(我们昨晚才偶然发现这个解决方案,所以它没有太多的老化时间。我们使用的是 Rails 3.2.8)
关于ruby-on-rails - Rails 3.2 错误路由问题。错误 ID 与其他对象 ID 冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9794406/