views:

286

answers:

2

I'm looking to make a show action of one of my controllers the root. I can easily do this:

map.root :controller => 'articles', :action => 'index'

When I go to localhost:3000/ it lists all the articles - that's great! What I want to achieve, though, is a URL like this

localhost:3000/1

To display an article with the id 1. Changing the route the the following would be what I'd think I have to do:

map.root :controller => 'articles', :action => 'show'

But it does not seem to work. Instead - it looks for a controller called 1 - which does not exist.

How would I go about doing this?

Thank you!

+3  A: 

Try this in routes.rb

map.connect ':id', :controller => 'articles', :action => 'show'

You'll want to make sure this is a low priority route because of how general it is. I.e., put it toward the bottom of your routes.rb file but above this section (if you haven't deleted it already):

# low-priorty article show route
map.connect ':id', :controller => 'articles', :action => 'show'

# Install the default routes as the lowest priority.
# Note: These default routes make all actions in every controller accessible via GET requests. You should
# consider removing or commenting them out if you're using named routes and resources.
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
macek
thank you. You were the first to give an answer so you're getting the credit. Thanks for the extra explanation in your edit.
yuval
+2  A: 

A root route define only one route. Not several. You can define another route

map.connect '/:id', :controller => 'articles', :action => 'show'

If you want this style of route, maybe a resources (http://api.rubyonrails.org/classes/ActionController/Resources.html#M000522) is great for you.

shingara
works, but now none of my other controllers are accessible. Any way around that?
yuval
and to answer my own question - make sure that this line of code is below any other ones you want to have priority. In routes.rb the higher the route in the list the higher the priority.
yuval
just a note, shingara; you don't need the `/` before `:id` :)
macek
yes it's not mandatory, but I found that much simplest to understand the real matching route
shingara