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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With