Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 Route with Multiple Optional Parameters

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!

like image 853
Eric Walsh Avatar asked Apr 07 '15 21:04

Eric Walsh


1 Answers

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

like image 150
Shalev Shalit Avatar answered Nov 11 '22 05:11

Shalev Shalit