首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >路由约束:不匹配时引发异常

路由约束:不匹配时引发异常
EN

Stack Overflow用户
提问于 2018-12-12 06:37:14
回答 2查看 163关注 0票数 0

给定如下的Rails路由约束:

代码语言:javascript
复制
class UserConstraint
  def matches?(request)
    User.where(code: request.path_parameters[:code]).any?
  end
end

这将无法工作,因为有一个子路由。

routes.rb

代码语言:javascript
复制
constraints UserConstraint.new do
  get ':code', to: 'documents#index', as: :documents
  get ':code/*slug', to: 'documents#show', as: :document
end

它只返回以下内容:

代码语言:javascript
复制
ActiveRecord::RecordNotFound:
Couldn't find User with 'slug'={:code=>"show"}

这是不是只能用更多的约束才能解决?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-12-12 08:09:34

对于任何寻找类似问题的答案的人来说,这就是我解决它的方法。虽然@colincr没有错,但它并没有确切地详细说明解决方案。

如果您有像我一样的全局路由,那么为它们编写单独的约束会更容易。

routes.rb

代码语言:javascript
复制
constraints UserConstraint.new do
  get ':code', to: 'documents#index', as: :documents
end

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

user_constraint.rb

代码语言:javascript
复制
class UserConstraint
  def matches?(request)
    result = User.where(code: request.path_parameters[:code]).any?
    raise Errors::NoCode, 'User not found' unless result

    result
  end
end

slug_constraint.rb

代码语言:javascript
复制
class SlugConstraint
  def matches?(request)
    slug = "#{request.path_parameters[:code]}/#{request.path_parameters[:slug]}"
    result = Document.where(slug: slug).any?
    raise Errors::NoDocumentSlug, 'Document not found' unless result

    result
  end
end
票数 0
EN

Stack Overflow用户

发布于 2018-12-12 06:50:43

将该查询赋给一个变量,并执行如下操作-

raise <ExceptionClass> unless variable

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53733412

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档