Rails 3 中的 url_for 和路由默认值
我的 Rails 路线设置如下:
match ':controller/:id/:action'
# match 'teams/:id' => "teams#show" # doesn't have any additional effect, which makes sense to me
resources :teams, :only => [:index, :show]
这样我就可以说 /teams/cleveland-indians
,它将使用 :id => 调用
。效果很好。我的问题是 teams#show
。 “克利夫兰印第安人”url_for
并不能完全满足我的要求。在我的views/teams/index 视图中,我得到了这种行为:
url_for(:id => "cleveland-indians") # => /teams/cleveland-indians/index
url_for(:id => "cleveland-indians", :action => :show) # => /teams/cleveland-indians/show
当然,第二个行为符合我想要的方式,但我想在最后删除不必要的 /show
。我不太了解这些助手是如何工作的,但我猜测它会知道 show
是具有指定 id 的 GET 的默认操作,与路由引擎相同。不管怎样,对我来说处理这件事最好的方法是什么?或者我只是做错了?
I have a rails route set up like:
match ':controller/:id/:action'
# match 'teams/:id' => "teams#show" # doesn't have any additional effect, which makes sense to me
resources :teams, :only => [:index, :show]
That way I can say /teams/cleveland-indians
and it will call teams#show
with :id => 'cleveland-indians'
. Works great. My issue is that url_for
doesn't quite do what I want. In my views/teams/index view, I get this behavior:
url_for(:id => "cleveland-indians") # => /teams/cleveland-indians/index
url_for(:id => "cleveland-indians", :action => :show) # => /teams/cleveland-indians/show
Of course that second one behaves the way I want, but I'd like to get rid of the unnecessary /show
at the end. I don't know much about how these helpers work, but I'd have guessed it would know that show
was the default action for a GET with a specified id, same as the routing engine does. Anyway, what's the best way for me to take care of this? Or am I just doing it all wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
“资源”行应该已经为您提供了您可能想要的路线,因此您可以删除第一个“匹配”行。
请注意,您还可以使用 'teams_path'、'team_path("cleveland-indians")' 而不是 'url_for'。
'resources' line should already provide you with the routes you probably want so you can just remove first 'match' line.
Note that you can also use 'teams_path', 'team_path("cleveland-indians")' instead of 'url_for'.