url_for和路由默认设置在Rails 3中

时间:2021-06-20 10:58:38

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:

这样,我就可以输入/teams/cleveland-indians,它会把team #show命名为:id => 'cleveland-indians'。伟大的工作。我的问题是url_for并没有完成我想要的。在我的观点/团队/索引视图中,我得到了这样的行为:

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?

当然第二种方式是我想要的,但是我想在最后摆脱不必要的/展示。我不太了解这些助手是如何工作的,但是我猜想它会知道show是带有指定id的GET的默认操作,就像路由引擎一样。不管怎样,对我来说最好的处理方法是什么?或者我只是做错了?

1 个解决方案

#1


1  

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

注意,您还可以使用'teams_path'、'team_path(“cleveland-indians”)而不是'url_for'。

#1


1  

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

注意,您还可以使用'teams_path'、'team_path(“cleveland-indians”)而不是'url_for'。