url_for and route defaults in Rails 3
-
24-10-2019 - |
Question
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?
Solution
'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'.