There is a lot of stuff in Rails that automatically does a lot for you. Out of that, resource takes a lot of importance, as it builds the basics of RESTful routing in your web application. Under the hood, it does a lot for us. Let’s tear it into individual pieces, and do that magic manually.
RESTful principles are famous for building web services that talk with clients, and that communication is independent of the nature of the clients. What follows is the essence of RESTful principles:
1. A client should send minimum information to the web service for the communication to take place.
2. A request should contain no information regarding the previous request. Each request should be independent of each other.
3. A request should only update only one row of one table in a database.
4. If the same request is fired multiple times, it should do the same as if the only one request has been fired.
Good news is that resource takes care of all of these principles in Rails. So it’s the time to break it down.
resources :users
The line above creates 7 routes in Rails. Let’s try to build those manually, and collectively these are gonna be as effective as resources :users.
get '/users/new'
As stated earlier, a client should send minimum information on the server to do a task. get ‘/users/new’ does the very same thing, as it requests to have something for creating a new user(resource) on the server. As of Rails 4, we don’t need to mention the name of controller and action within that controller – Rails will interpret this thing automatically for us.
get '/users/:id' => 'users#show'
This route will get us back a single resource. It simply uses get request and sends over the id of the resource a client would like to have.
post '/users' => 'users#create'
This route will try to create a new user, and this route will go towards create action inside users controller.
get '/users/:id/edit' => 'users#edit'
This route will try to get an edit page, through which a client would be able to update an existing user.
patch '/users/:id' => 'users#update'
This route will be used to update an existing resource in the database.
To get all the rows in a particular table, we’d use the following route:
get '/users' => 'users#index'
At the end, to delete a record in a particular table, we’d use DELETE http verb, with the minimum information: the name of the table and something along that uniquely identifies the record to be deleted.
delete '/users/:id' => 'users#destroy'
Sometimes, we take the things granted, but breaking the things down to the bottom level will definitely give us deep insights on how the things actually work and strengthen our overall understanding. What you think of this approach, kindly let us know in the comments section below. Happy routing!