In this second part of a four-part article series on creating an online bookstore application with Ruby on Rails, you'll learn how to run a migration script and unit tests, create the controller, and more. This article is excerpted from chapter two of the book Practical Rails Projects, written by Eldon Alameda (Apress; ISBN: 1590597818).
Adding Authors to an Online Bookstore - Creating the Controller (Page 3 of 4 )
As explained in Chapter 1, a controller is the central part of an application that takes care of receiving the user request, modifying data through the model part, and finally either rendering a view template or redirecting the user to another URL. Now that we have the ActiveRecord model for authors in place, we need a controller that implements the administration interface for authors. From that last sentence, we can already pick a good name for the controller: admin/author.
You create a controller by using the samescript/generatecommand that you use to create a model. You can also give thegenerate controllercommand names of the actions you want the controller to implement—in this case,new,create,edit,update,destroy,show, andindex.
$ script/generate controller 'admin/author' new create edit update➥ destroy show index
By usingadmin/authorinstead of justauthoras the controller name, we put theauthorcontroller inside anadminsubdirectory. The newAuthorControllerclass is also set inside a module calledAdmin. This way, we can later implement other administrative controllers under the same module and make them share common code such as access control.
Just as for models, thegeneratecommand created a controller stub and empty views for all actions for us. It also created a functional test file for our controller.
Note If you haven’t already done so, now would be a good time to put your code under source control. We prefer Subversion, as it’s the norm in the Rails world, but the most important thing is that you use some kind of source control management. You wouldn’t want to tell George that you lost a whole day’s worth of code, would you?