【问题标题】:How to match parameters with dots in Rails 4 constraints?如何将参数与 Rails 4 约束中的点匹配?
【发布时间】:2014-12-08 04:00:00
【问题描述】:

这听起来很简单。我正在尝试做的是使用单独的类来允许带有多个点的参数的段约束。

这很好用:

# /config/routes.rb
get '/photos/:id', to: 'photos#show', constraints: { id: /[A-Z]+[0-9\.]+/ }

我正在尝试将约束放在一个类中。

# /config/routes.rb
get '/photos/:id', to: 'photos#show', constraints: PhotosConstraint.new

还有这个约束类:

# /lib/photos_constraint.rb
class PhotosConstraint
  def matches?(request)
    request[:id] =~ /[A-Z]+[0-9\.]+/
  end
end

当我尝试访问路由时,它会返回路由错误。

ActionController::RoutingError (No route matches [GET] "/photos/id_with_._dot_and_._dot")

【问题讨论】:

  • 尝试在 [A-Z]+[0-9\.]/ 之后添加 i ?
  • @argentum47 谢谢。如果我在id 中有一个点,它工作正常,但是当我尝试有多个点时,它无法正确路由。我更新了我的问题。
  • 这很酷,您需要了解正则表达式。 + 或 * 符号通常用于(重复),但您需要学习。
  • @argentum47,这很酷。唯一的区别是,当您将正则表达式放在路由中时,它有效,但如果您将它放在一个类中,它不起作用
  • 这怎么可能.. 尝试调试它。通过撬动或通过 'p' 变量并检查值。

标签: ruby-on-rails ruby ruby-on-rails-4 routing routes


【解决方案1】:

这应该可行:

# /config/routes.rb 
get '/photos/:id', to: 'photos#show', id: /[A-Z]+[0-9\.]+/, constraints: PhotosConstraint.new

【讨论】:

  • 这会起作用,但我需要删除路由内的正则表达式并将其放入类中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-06
  • 1970-01-01
  • 2013-06-09
相关资源
最近更新 更多