Routing with an optional parameter

Ruby on-RailsRoutingRails RoutingRuby on-Rails-2

Ruby on-Rails Problem Overview


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

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

[Put the optional parts between parenthesis][1]:

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

[1]: http://guides.rubyonrails.org/routing.html#bound-parameters "Rails Guides - Routing - bound parameters"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlessandro De SimoneView Question on Stackoverflow
Solution 1 - Ruby on-RailsBenoit GarretView Answer on Stackoverflow