4.1. Using the Scaffold MethodWe've already demonstrated a working model for Photo Share, including photos, categories, slideshows, and slides, and you should be able to manage schema from Active Record objects with the Rails console. The next step is to use scaffolding to build primitive web user interfaces for these classes. Scaffolding will take you a good ways down the road, but it won't generate a completed application. That's okay. We're looking for a head start, not a completed production-quality application. 4.1.1. A List of PhotosLet's start by letting the user manage a list of photos from the Web. Ensure that you've got a database, that it's configured, and that you've got tables with model objects for slides, slideshows, categories, and photos. [*] If your server is not started, restart it as usual with ruby script/server . Point your browser to http://localhost:3000/ to make sure things are working. You'll see the Rails welcome page if everything is working correctly. Let's build some scaffolding.
You'll start to build scaffolding using the scaffold method. That method goes into the controller, so we need to generate a controller called Photos: ruby script/generate controller Photos Add the scaffold :photo method to photo_controller.rb , like this: class PhotosController < ApplicationController scaffold :photo end That's all you needRails will do the rest. Now, load the URL http://localhost:3000/photos to see the scaffolding in action. You'll see a list of photos, with links to create new photos, edit existing photos, and show existing photos. With the simple scaffold :photo statement, you got all the pages that show in Figure 4-1. The scaffolding generates surprisingly complete controller and view code. To be sure, the scaffolding does not generate production-ready code, but it's a starting point. The next section shows how scaffolding works. Figure 4-1. Scaffolding renders all four of these views
4.1.2. More Metaprogrammingscaffold :photo does the magic. scaffold is a method on ActionController . [ ] :photo is a symbol that determines the Active Record model that Rails uses for this scaffold. When you specify this single method, Rails adds to your controller the nine methods in Table 4-1. Four of them render views. Together, the methods build a simple CRUD interface for your Active Record model based on the model object. Within the model, the @@content_columns attribute contains information about each of the columns in the database.
Table 4-1. The scaffold :target method on a Rails controller creates the methods on the controller
Most of the methods listed in Table 4-1 wind up calling the render_scaffold method, which checks to see whether you've added the corresponding view. (Remember that by default, Rails views will have the same name as the controller method.) If so, Rails uses your views. Otherwise, the controller provides default views. |