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

时间:2022-03-22 08:28:47

I am trying to create a Rails route that has optional parameters as well as varying order.

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

This question describes a similar problem: Routes with multiple, optional, and pretty parameters

这个问题描述了一个类似的问题:具有多个,可选和漂亮参数的路由

I am trying to create routes that have map filters in them, like parameters but without the parameter URL styling. The idea is to have them look like

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

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

but you should also be able to search with

但你也应该能够搜索

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

I know that I could write complex regex statements with route globbing - however I'm wondering if there is a way to have multiple optional route parameters with unspecified order, something like

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

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

Thanks!

1 个解决方案

#1


2  

You can use the constraints with lambda to use multiple search options:

您可以使用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)

You can make a different lambda for more complex routes

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

#1


2  

You can use the constraints with lambda to use multiple search options:

您可以使用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)

You can make a different lambda for more complex routes

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