Tuesday, December 10, 2013

Rails router, route, path, URL, resource routing

When it come to routing, there is a lot of confusing terms. In this blog, I'll try to shed some light on their meanings.

Router
Rails router is just a piece of code that handles HTTP verb and URL combos and dispatch them to a controller's action.

Route
Route is just the mapping from HTTP verb and URL combo to controller's action.
For example
get '/patients/:id', to: 'patients#show'

Path vs URL
Paths and URLs are easy to be confused.
Say we have a users controller, we can have a path and a URL for it, shown below.
Path => /users
URL => http://www.example.com/users
As we can see here, URLs are just paths prefixed with the current host, port and path prefix.

Resource Routing
In Rails, resource routing allows you to quickly declare all of the common routes for a given resourceful controller by using a single line. For example, you have a controller called photos.

resource :photos

By adding this line into our routes.rb file, we creates the following seven routes.

HTTP VerbPathActionUsed for
GET/photosindexdisplay a list of all photos
GET/photos/newnewreturn an HTML form for creating a new photo
POST/photoscreatecreate a new photo
GET/photos/:idshowdisplay a specific photo
GET/photos/:id/editeditreturn an HTML form for editing a photo
PATCH/PUT/photos/:idupdateupdate a specific photo
DELETE/photos/:iddestroydelete a specific photo
For example, if Rails application receives a incoming request for 
GET /photos/1
The router would dispatch that request to the show action in the photos controller with {id: '1'} in params.

1 comment:

  1. Excellent article. Very interesting to read. I really love to read such a nice article. Thanks! keep rocking.Ruby on Rails Online Course

    ReplyDelete