Brian
Brian

Reputation: 7145

Why does Rails order the 7 routes created from :resources the way it does?

This is pure curiosity. Let's say I have a resource "Users" and want to create the standard set of 7 routes for it. In my routes file, I simply enter resources :users. When running rake routes, this is what we get:

     users GET    /users(.:format)           users#index
           POST   /users(.:format)           users#create
  new_user GET    /users/new(.:format)       users#new
 edit_user GET    /users/:id/edit(.:format)  users#edit
      user GET    /users/:id(.:format)       users#show
           PUT    /users/:id(.:format)       users#update
           DELETE /users/:id(.:format)       users#destroy

Is there a specific reason that it's ordered like this? I understand that the first route that matches the request will be used.

My confusion stems from my thought process that the users#show route would be listed 3rd instead of users#new being in that position.

If anyone could give me some insight into this ordering scheme that would be great.

Upvotes: 2

Views: 907

Answers (3)

Thong Kuah
Thong Kuah

Reputation: 3283

I read them as starting from the :collection routes and the :new routes, then the :member routes.

Upvotes: 0

pjmorse
pjmorse

Reputation: 9294

If users#show was listed third, then /users/new would try to show the user with :id "new".

Upvotes: 1

Ryan Bigg
Ryan Bigg

Reputation: 107728

There's no particular reason why these are the way that they are, they just are that way.

It probably stems from the old (I'm talking 1.2 days here) scaffold controller layout where the actions were laid out in that order.

The only problem I can imagine you would encounter here is that if you were to have a user with the id of new it would go to UsersController#new first, rather than the ideal UsersController#show. The workaround for that is fairly simple: don't let users identify themselves as "new".

Upvotes: 2

Related Questions