路线限制:没有匹配项时引发异常

时间:2018-12-11 22:37:14

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

给出如下所示的Rails路线约束:

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

由于子路由,这将无法正常工作。

routes.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"}

这只能解决更多的限制吗?

2 个答案:

答案 0 :(得分:0)

将该查询分配给变量,然后执行以下操作-

raise <ExceptionClass> unless variable

答案 1 :(得分:0)

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

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

routes.rb

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

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

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