具有多个可选参数的Rails 3路线 [英] Rails 3 Route with Multiple Optional Parameters

查看:59
本文介绍了具有多个可选参数的Rails 3路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

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

/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/

我知道我可以使用路由遍历功能编写复杂的regex语句-但是我想知道是否有一种方法可以使多个可选的路由参数具有未指定的顺序,例如

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) )

谢谢!

推荐答案

您可以将约束与lambda一起使用以使用多个搜索选项:

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

  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

You can make a different lambda for more complex routes

这篇关于具有多个可选参数的Rails 3路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆