Ruby on rails 具有多个可选参数的Rails 3路线

Ruby on rails 具有多个可选参数的Rails 3路线,ruby-on-rails,routing,Ruby On Rails,Routing,我正在尝试创建一个具有可选参数和不同顺序的Rails路由 此问题描述了一个类似的问题: 我正在尝试创建包含地图过滤器的路由,比如参数,但没有参数URL样式。我们的想法是让它们看起来像 /search/country/:country/ /search/country/:country/state/:state/ /search/country/:country/state/:state/loc/:lat/:long/ 但是你也应该能够用 /search/state/:state/ /searc

我正在尝试创建一个具有可选参数和不同顺序的Rails路由

此问题描述了一个类似的问题:

我正在尝试创建包含地图过滤器的路由,比如参数,但没有参数URL样式。我们的想法是让它们看起来像

/search/country/:country/
/search/country/:country/state/:state/
/search/country/:country/state/:state/loc/:lat/:long/
但是你也应该能够用

/search/state/:state/
/search/state/:state/country/:country/
/search/loc/:lat/:long/
我知道我可以用route globbing编写复杂的regex语句,但是我想知道是否有一种方法可以让多个可选的route参数具有未指定的顺序,比如

/search/( (/country/:country)(/state/:state)(/loc/:lat/:long) )

谢谢

您可以对lambda使用
约束来使用多个搜索选项:

  search_options = %w(country state loc)
  get('search/*path',:to => 'people#search', constraints: lambda do |request|
             extra_params = request.params[:path].split('/').each_slice(2).to_h
             request.params.merge! extra_params # if you want to add search options to params, you can also merge it with search hash
             (extra_params.keys - search_options).empty?
           end)

您可以为更复杂的路线制作不同的lambda

我认为您已经有了解决问题的最佳解决方案,即regexpOne其他方式,可能不是最好的,就是在你的
路由中有多个条目。rb
我用Regex解决了这个问题,但我仍然好奇Rails5协议是否需要支持多个可选参数。您应该能够指定分隔符,并在显式和欠序之间进行选择。@RPinel是的,这是一个解决方案,但它不适用于许多参数,因为N个参数将对应于N!路由文档中的路由数量。在这种情况下,正则表达式将是一个明显的选择!谢谢,这似乎是解决这个问题的好方法。我想最终还是要像你说的那样在复杂的lambda中使用regex,希望他们能在Rails 5中添加简单的多个可选参数支持!