给定如下的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"}
这是不是只能用更多的约束才能解决?
发布于 2018-12-12 08:09:34
对于任何寻找类似问题的答案的人来说,这就是我解决它的方法。虽然@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
发布于 2018-12-12 06:50:43
将该查询赋给一个变量,并执行如下操作-
raise <ExceptionClass> unless variable
https://stackoverflow.com/questions/53733412
复制相似问题