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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 01:54:13  来源:igfitidea点击:

Routing with an optional parameter

ruby-on-railsroutingrails-routingruby-on-rails-2

提问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 及以上版本。反转两个路由定义解决了这个问题(见下面亚历山德罗的评论)。