Tuesday, August 11, 2015

Having Fun with Rails Routes

So, being a newbie in Rails, all I used to do in routes.rb was

resources :users  (you can replace users with any model name in plural)

resource :user

resources :users do
      resources :photos
end

A friend of mine asked me to checkout these four commands, I am just writing what will happen in detail.

Created a new project using

rails _3.2.3_ new testapp -d mysql

Set your current directory to the project directory
cd testapp

Generate Scaffold
rails g scaffold users name:string

Create MySQL databases
rake db:create

Run the migrations that have not been run yet (In short, your users table will be created in testapp_development database)
rake db:migrate

Then I did the messing with config/routes.rb and checked out the routes available on terminal, using rake routes | grep user command

1. resources :users
                     
Nothing new. Creates your 7 routes that you already know how to use if you have ever generated scaffold in rails.

2. resource :user
                    Index page route will not be created. User will be treated as a singular resource. Total 6 routes will be generated as follows. Accessed through URL by using /user/

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

3. resources :user
                   Now this one is a bit problematic. The routes are created as follows:
GET    /user(.:format)          user#index
POST   /user(.:format)          user#create
GET    /user/new(.:format)      user#new
GET    /user/:id/edit(.:format) user#edit
GET    /user/:id(.:format)      user#show
PUT    /user/:id(.:format)      user#update
DELETE /user/:id(.:format)      user#destroy

But what happens is that we are looking for the actions in the UserController, but the convention is that the controller name is in plural, ie UsersController. So we'll get an uninitialized constant error if we try to access through /user/ in URL.

4. resource :users
                 Creates your usual singular resources, that will be accessed by /users/ instead of /user/ in URL.

POST   /users(.:format)      users#create
GET    /users/new(.:format)  users#new
GET    /users/edit(.:format) users#edit
GET    /users(.:format)      users#show
PUT    /users(.:format)      users#update
DELETE /users(.:format)      users#destroy


Powered by Blogger.