Rails 3 Route with Multiple Optional Parameters

不羁的心 提交于 2019-12-05 21:18:30

问题


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

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/

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:


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)

You can make a different lambda for more complex routes



来源:https://stackoverflow.com/questions/29501364/rails-3-route-with-multiple-optional-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!