Code and Development

CRUD, Routes, and Rails

A very important concept in Ruby on Rails is CRUD and Resourceful routes. CRUD stands for Create, Read, Update, and Destroy operations in a database. Resourceful routes are used to declare objects as a resource in the routes file ( usually routes.rb). These two concepts are directly related through HTTP verbs, URLs, and controller actions .

For example, by declaring “resources :photos” in the routes.rb file, 7 different routes are created that match to the “Photos” controller. The seven routes are shown below:

Screen Shot 2015-02-24 at 4.02.00 PM

By taking a look at this table, lets break down what each column means. The first column shows the HTTP verb request for each action. The Path column shows the actual page url for each action. The Controller#Action column displays the controller that is being used and the action that is being called. In our case, the Controller is the Photos Controller. The Used for column gives a brief explanation of the usage of each controller action.

So for example, if I have a website that allows users to upload pictures online and I wanted to see all the photos that are online, I would use a GET request with a url of “www.websitename.com/photos”. The routes.rb file will route this request to the photos controller and this works because we have declared “resources :photos“. Once routed to the photos controller, the index action will be found in that controller. At this point, it is up to your controller action and the view to provide all of the photos to the user.

That was a brief overview of restful routes and CRUD. Hope you enjoyed it!

-Weijie

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s