Search code examples
ruby-on-railsroutesrails-routingruby-on-rails-2

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


Solution

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