Ruby-on-rails 带有可选参数的路由
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7281592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Routing with an optional parameter
提问by Alessandro DS
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.
但它不起作用,如果我不通过年份,它在“show_book/NAME”中找不到路线。
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
附注。我知道我可以使用“?year=XXXX”作为参数使用年份,但我想使用年份作为 URL 的一部分
回答by Benoit Garret
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).
以上答案仅适用于 rails 3 及以上版本。反转两个路由定义解决了这个问题(见下面亚历山德罗的评论)。

![Ruby-on-rails rails 3.1 ActionController::RoutingError(没有路由匹配 [GET]](/res/img/loading.gif)