【问题标题】:Optional parameter with constraint in the middle of Rails route在 Rails 路线中间有约束的可选参数
【发布时间】:2013-09-02 23:36:42
【问题描述】:

是否可以对 'in the middle'可选 路由参数进行约束?

我想要以下路线:

get ':city(/:suburb)/:venue_type', venue_type: /bar|restaurant|cafe/

这将显示位于城市的特定类型的场所列表,或者可以选择将其缩小到郊区。我支持的唯一:venue_typesbar, restaurantcafe

现在我想实现以下映射:

/nyc/manhattan/bar -> :city = nyc, :suburb = manhattan, :venue_type = bar
/nyc/bar           -> :city = nyc, :suburb = (nil),     :venue_type = bar
/nyc/whatever/cafe -> :city = nyc, :suburb = whatever,  :venue_type = cafe
/nyc/whatever      -> :city = nyc, :suburb = whatever,  :venue_type = (nil) - routing error

到目前为止,我已经尝试过以下无法完成工作的方法:

class ValidSuburb
  INVALID = %w[bar restaurant cafe]
  def self.matches?(request)
    request.params.has_key?(:suburb) && !INVALID.include?(request.params[:suburb])
  end
end
get ':city(/:suburb)/:venue_type', venue_type: /bar|restaurant|cafe/, suburb: ValidSuburb.new

这是否可能通过约束来实现,还是我必须求助于多条路线?

【问题讨论】:

    标签: ruby-on-rails routing constraints


    【解决方案1】:

    也许我遗漏了一些东西,但只有 2 条路线不是更简单吗?

    get ':city/:venue_type', constraints: { venue_type: /bar|restaurant|cafe/ }
    get ':city/:suburb/:venue_type', constraints: { venue_type: /bar|restaurant|cafe/ }
    

    这里,如果除了"bar""restaurant""cafe" 之外的任何其他内容作为/nyc/.../bar 之后的片段传递,第一个路由将被跳过,允许它与第二个路由匹配。

    如果 /nyc/whatever 被传递,它将不符合任一路由的约束/格式,从而导致您所追求的 RouteError。

    【讨论】:

    • 是的,这就是我不得不求助的方法。但是,我会欢迎基于约束的解决方案,因为我的“真实”路线需要多条参数,并且不重复它会很方便。
    • 这就是为什么在某些情况下最好淡化你的问题。
    猜你喜欢
    • 1970-01-01
    • 2011-03-28
    • 2019-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 2012-10-02
    • 2017-11-02
    相关资源
    最近更新 更多