Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails routes multiple optional parameters

I have a question, how can you make multiple optional params. F.e. in my variant, I need similar thing to "/(:first_name || :last_name || middle_name || all_names)". How can I achieve and can I achieve such thing in routes?

Btw, it'd be nice if I can do a lot of multiple params f.e.:

/(:a || :b || :c)/(:d || :e)/(:n || :m)

Thanks for answering.

like image 434
Oleksandr Verhun Avatar asked Aug 17 '26 09:08

Oleksandr Verhun


1 Answers

You'll have to do all the conditional work in the controller - the routes are there to capture request URLs & direct them to specific functionality (controller/actions).

Thus, your question of using

/(:a || :b || :c)/(:d || :e)/(:n || :m)

... is fundamentally flawed (you can't have condition "or" in Routes).


What you can have is bound parameters:

enter image description here

These are optional params which a route can take, but doesn't have to.

In your case, you'll need to use them to denote the name as passed:

#config/routes.rb
resources :users, path: "" do
   get :first_name(/:middle_name(/:last_name)), action: :show, on: :collection
end

This is the best you're going to get without doing something custom in the routing system... like having slugs or something.

like image 196
Richard Peck Avatar answered Aug 19 '26 04:08

Richard Peck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!