-->

Routing with an optional parameter

2019-02-01 15:59发布

问题:

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

回答1:

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