【问题标题】:Route constraints: raising exception when there's no match路由约束:没有匹配时引发异常
【发布时间】:2018-12-11 22:37:13
【问题描述】:

给定这样的 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"}

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

【问题讨论】:

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


    【解决方案1】:

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

    raise <ExceptionClass> unless variable

    【讨论】:

      【解决方案2】:

      对于任何寻找类似问题答案的人来说,这就是我解决它的方法。虽然@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
      

      【讨论】:

        猜你喜欢
        • 2014-04-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-16
        • 2012-10-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多