Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Routing with an optional parameter

I added in the route file:

map.show_book "/show_book/:name/year/:year", :controller => "book", :action => "show_version" 

I also added:

map.show_book "/show_book/:name", :controller => "book", :action => "show_version" 

to show the latest book without specifying the year.

But it doesn't work, it cannot find the route in "show_book/NAME" if I don't pass the year.

Do you have some ideas why it doesn't work ?

THANKS !

PS. I know that I can use year as parameter with "?year=XXXX", but I want to use the year as a part of the URL

like image 358
Alessandro De Simone Avatar asked Sep 02 '11 09:09

Alessandro De Simone


People also ask

How do you pass optional parameters in react router?

To add in an optional path parameter in React Router, you just need to add a ? to the end of the parameter to signify that it is optional. And then in your component you could access the GET parameters using the location.search prop that is passed in by React Router.

What is a optional parameter?

A method that contains optional parameters does not force to pass arguments at calling time. It means we call method without passing the arguments. The optional parameter contains a default value in function definition. If we do not pass optional argument value at calling time, the default value is used.

How would you implement optional parameters?

To implement the optional parameter first you need to add System. Runtime. InteropServices namespace in your program, then creates an optional parameter using the Optional keyword enclosed in square brackets before the definition of the parameter in the method. The default value of OptionalAttribut is zero.


1 Answers

Put the optional parts between parenthesis:

map.show_book "/show_book/:name(/year/:year)", :controller => "book", :action => "show_version" 

and remove the second route.

Update

The above answer is only for rails 3 and above. Inverting the two routes definitions fixed the problem (see Alessandro's comment below).

like image 139
Benoit Garret Avatar answered Sep 21 '22 12:09

Benoit Garret