Routing with an optional parameter

Alessandro De Simone picture Alessandro De Simone · Sep 2, 2011 · Viewed 31.8k times · Source

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

Answer

Benoit Garret picture Benoit Garret · Sep 2, 2011

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).