Routing with an optional parameter

2019-02-01 16:20发布

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条回答
甜甜的少女心
2楼-- · 2019-02-01 16:53

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

查看更多
登录 后发表回答