Rails 3路由具有多个可选参数

时间:2015-04-07 21:09:56

标签: ruby-on-rails routing

我正在尝试创建一个Rails路由,该路由具有可选参数以及不同的顺序。

此问题描述了类似的问题:Routes with multiple, optional, and pretty parameters

我正在尝试创建包含地图过滤器的路线,例如参数但没有参数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/

我知道我可以使用路由通配来编写复杂的正则表达式语句 - 但是我想知道是否有一种方法可以使用未指定顺序的多个可选路由参数,例如

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

谢谢!

1 个答案:

答案 0 :(得分:2)

您可以将constraints与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

相关问题