Rails 3 中的 url_for 和路由默认值

发布于 2024-10-22 01:54:17 字数 795 浏览 1 评论 0原文

我的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

源来凯始玺欢你 2024-10-29 01:54:18

“资源”行应该已经为您提供了您可能想要的路线,因此您可以删除第一个“匹配”行。

请注意,您还可以使用 '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'.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文