Rails 3 条带有多个可选参数的路由
Rails 3 Route with Multiple Optional Parameters
我正在尝试创建一个 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) )
谢谢!
您可以使用 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
我正在尝试创建一个 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) )
谢谢!
您可以使用 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