首页 > 解决方案 > 路由约束:没有匹配时引发异常

问题描述

给定这样的 Rails 路由约束:

class UserConstraint
  def matches?(request)
    User.where(code: request.path_parameters[:code]).any?
  end
end

由于子路由,这将不起作用。

路线.rb

constraints UserConstraint.new do
  get ':code', to: 'documents#index', as: :documents
  get ':code/*slug', to: 'documents#show', as: :document
end

它只返回以下内容:

ActiveRecord::RecordNotFound:
Couldn't find User with 'slug'={:code=>"show"}

这只能通过更多的约束来解决吗?

标签: ruby-on-railsroutingruby-on-rails-5

解决方案


将该查询分配给一个变量并执行类似的操作-

raise <ExceptionClass> unless variable


推荐阅读