0

是否可以对位于路线“中间”的可选路线参数进行约束?

我想有以下路线:

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

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

现在我想实现以下映射:

/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

这是否可以通过限制来实现,还是我必须求助于多条路线?

4

1 回答 1

1

也许我错过了一些东西,但只有两条路线不是更简单吗?

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

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

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

于 2013-09-03T00:32:07.020 回答