In this post we are going to take a look at a typical CRUD controller in Rails. We will use a modified version of the controller generated by the command that we can in Part 3:
rails g scaffold Baby name:string age:integer
If we remember, this generated a ton of stuff for us (which can be good and bad), one of which was a controller called BabiesController. If you look in the controller you’ll see that a bunch of actions are in there. These actions were generated with important names, and one way to see that is by looking in our routes.rb file. In this file we will see that our entire controller is being wired up by one line:
So here we see what Rails calls a "resource route". It is a route which supports a common set of actions to support RESTful controllers. The standard actions supported are these:
- index – Shows a list of all saved models.
- show – Display a single read-only view of a model.
- new – Renders a form to create a new model.
- edit – Finds a model, then renders a form to edit it.
- create – Where a new model is posted to be saved.
- update – Where the edit form posts to be saved.
- destroy – Deletes a model.
If you can, it is a good idea to use the resource routes and stick with the default naming. It’ll save a ton of typing and make thing more predictable. And don’t think that it’ll lock you down, the resource routes are completely configurable. You can add in custom routes and opt out of specific routes.