English 中文(简体)
Rails 2.1 Scaffolding
  • 时间:2024-11-03

Ruby on Rails 2.1 - Scaffolding


Previous Page Next Page  

While you re developing Rails apppcations, especially those which are mainly providing you with a simple interface to data in a database, it can often be useful to use the scaffold method.

Scaffolding provides more than cheap demo thrills. Here are some benefits −

    You can quickly get code in front of your users for feedback.

    You are motivated by faster success.

    You can learn how Rails works by looking at generated code.

    You can use the scaffolding as a foundation to jumpstart your development.

Scaffolding Example

Ruby on Rails 2.0 changes the way Rails uses scaffolding. To understand scaffolding, let’s create a database called cookbook and a table called recipes. −

Creating an Empty Rails Web Apppcation

Open a command window and navigate to where you want to create this cookbook web apppcation. We used c: uby. Run the following command to create complete directory structure and required .yml file MySQL database.

C:
uby> rails -d mysql cookbook

Here we are using -d mysql option to specify our interest to use MySQL database. We can specify any other database name pke oracle or postgress using -d option. By default, Rails uses SQLite database.

Setting Up the Database

Here is the way to create database −

mysql> create database cookbook;
Query OK, 1 row affected (0.01 sec)

mysql> grant all privileges on cookbook.*
 to  root @ localhost  identified by  password ;
Query OK, 0 rows affected (0.00 sec)

mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)

To instruct Rails to locate the database, edit the configuration file ~cookbookconfigdatabase.yml and change the database name to cookbook. When you finish, it should look as follows −

development:
   adapter: mysql
   encoding: utf8
   database: cookbook
   username: root
   password: password
   host: localhost
test:
   adapter: mysql
   encoding: utf8
   database: cookbook
   username: root
   password: password
   host: localhost
production:
   adapter: mysql
   encoding: utf8
   database: cookbook
   username: root
   password: password
   host: localhost

NOTE − You can use similar settings for other database adapters in case you want to use any other database except MySQL.

Rails lets you run in the development mode, test mode, or production mode, using different databases. This apppcation uses the same database for each.

Database Table Definition

Assuming the following structure for our recipes table −

id INT(11) 
title VARCHAR(40)
chef VARCHAR(40)
instructions VARCHAR(255)

The Generated Scaffold Code

With the scaffold action, Rails generates all the code it needs dynamically. By running scaffold as a script, generate the model, plus scaffolding, and the database migration script needed as well as a controller, helper, and testing support files as follows −

cookbook> ruby script/generate scaffold Recipe title:string 
chef:string instructions:text 

Note a singular name Recipe to create a plural table name recipes. However, the above command will generate the following messages −

   exists  app/models/
   exists  app/controllers/
   exists  app/helpers/
   create  app/views/recipes
   exists  app/views/layouts/
   exists  test/functional/
   exists  test/unit/
   exists  pubpc/stylesheets/
   create  app/views/recipes/index.html.erb
   create  app/views/recipes/show.html.erb
   create  app/views/recipes/new.html.erb
   create  app/views/recipes/edit.html.erb
   create  app/views/layouts/recipes.html.erb
   create  pubpc/stylesheets/scaffold.css
   create  app/controllers/recipes_controller.rb
   create  test/functional/recipes_controller_test.rb
   create  app/helpers/recipes_helper.rb
   route  map.resources :recipes
dependency  model
   exists    app/models/
   exists    test/unit/
   exists    test/fixtures/
   create    app/models/recipe.rb
   create    test/unit/recipe_test.rb
   create    test/fixtures/recipes.yml
   create    db/migrate
   create    db/migrate/20080614192220_create_recipes.rb
cookbook>

Now, let s examine what has happened behind the scene.

The Controller

Let s look at the code behind the controller. This code is generated by the scaffold generator. If you open app/controllers/recipes_controller.rb, you will find something as follows −

class RecipesController < ApppcationController
   # GET /recipes
   # GET /recipes.xml
   def index
      @recipes = Recipe.find(:all)

      respond_to do |format|
         format.html # index.html.erb
         format.xml  { render :xml => @recipes }
      end
   end

   # GET /recipes/1
   # GET /recipes/1.xml
   def show
      @recipe = Recipe.find(params[:id])

      respond_to do |format|
         format.html # show.html.erb
         format.xml  { render :xml => @recipe }
      end
   end

   # GET /recipes/new
   # GET /recipes/new.xml
   def new
      @recipe = Recipe.new

      respond_to do |format|
         format.html # new.html.erb
         format.xml  { render :xml => @recipe }
      end
   end

   # GET /recipes/1/edit
   def edit
      @recipe = Recipe.find(params[:id])
   end

   # POST /recipes
   # POST /recipes.xml
   def create
      @recipe = Recipe.new(params[:recipe])

      respond_to do |format|
      if @recipe.save
         flash[:notice] =  Recipe was successfully created. 
         format.html { redirect_to(@recipe) }
         format.xml  { render :xml => 
            @recipe, :status => :created, :location => @recipe }
      else
         format.html { render :action => "new" }
         format.xml  { render :xml => 
            @recipe.errors, :status => :unprocessable_entity }
         end
      end
   end

   # PUT /recipes/1
   # PUT /recipes/1.xml
   def update
   @recipe = Recipe.find(params[:id])

   respond_to do |format|
      if @recipe.update_attributes(params[:recipe])
         flash[:notice] =  Recipe was successfully updated. 
         format.html { redirect_to(@recipe) }
         format.xml  { head :ok }
      else
         format.html { render :action => "edit" }
         format.xml  { render :xml => @recipe.errors, 
                      :status => :unprocessable_entity }
      end

   end

   # DELETE /recipes/1
   # DELETE /recipes/1.xml
   def destroy
      @recipe = Recipe.find(params[:id])
      @recipe.destroy
      
      respond_to do |format|
         format.html { redirect_to(recipes_url) }
         format.xml  { head :ok }
      end
   end
end

This file has all the methods implemented automatically. You can perform any Create, Read, Delete, or Edit operation using these available methods.

When a user of a Rails apppcation selects an action, e.g., "Show" - the controller will execute any code in the appropriate section - "def show" - and then by default will render a template of the same name - "show.html.erb". This default behavior can be overwritten by overwriting the code in any template. −

The controller uses ActiveRecord methods such as find, find_all, new, save, update_attributes, and destroy to move data to and from the database tables. Note that you do not have to write any SQL statements, Rails will take care of it automatically.

The Views

All the views and corresponding controller methods are created by scaffold command and they are available in app/views/recipes directory. You will have the following files in this directory −

    index.html.erb − This is the template file to show the default page and will be executed when you type http://127.0.0.1:3000/recipes.

    new.html.erb − This is the template to create a new recipe and will be executed whenever you will try to create a new recipe.

    show.html.erb − This is the template to show all the recipes in your database and will be executed whenever you will try to see all the recipes.

    edit.html.erb − This is the template to edit any recipe in your database and will be executed whenever you will try to edit any recipe.

We suggest you to open these files one by one and try to understand their source code.

The Migrations

You will find a migration file created in ~/cookbook/db/migrate subdirectory. This file will have the following content −

class CreateRecipes < ActiveRecord::Migration
   def self.up
      create_table :recipes do |t|
         t.string :title
         t.string :chef
         t.text :instructions
         t.timestamps
      end
   end

   def self.down
      drop_table :recipes
   end
end

To create the required file in your database, make use of helper script as follows.

cookbook> rake db:migrate

This command will create recipes and schema_migrations tables in your cookbook database. Before proceeding, please make sure you have the required table created successfully in your database.

Ready to Test

All the above steps bring your database table to pfe. It provides a simple interface to your data, and ways of −

    Creating new entries

    Editing current entries

    Viewing current entries

    Destroying current entries

When creating or editing an entry, scaffold will do all the hard work of form generation and handpng. It will even provide clever form generation, supporting the following types of inputs −

    Simple text strings

    Text areas (or large blocks of text)

    Date selectors

    Date-time selectors

Now, go to cookbook directory and run the Web Server using the following command −

cookbook> ruby script/server

Now, open a browser and navigate to http://127.0.0.1:3000/recipes/new. It will provide you a screen to create new entries in recipes table. A screenshot is shown below −

Create Recipe

Now, enter some values in the given text boxes, and press the Create button to create a new recipe. Your record is added into the recipes table and it shows the following result −

Added Recipe

You can use either the Edit option to edit the recipe or the Back button to go to the previous page. Assuming you have pressed the Back button, it will display all the recipes available in your database. As we have only one record in our database, it will show you the following screen −

Back Recipe

This screen gives you the option to see the complete details of the recipe table. In addition, it provides options to edit or even delete the table.

Enhancing the Model

Rails gives you a lot of error handpng for free. To understand this, add some vapdation rules to the empty recipe model −

Modify ~/cookbook/app/models/recipe.rb as follows and then test your apppcation −

class Recipe < ActiveRecord::Base
   vapdates_length_of :title, :within => 1..20
   vapdates_uniqueness_of :title, :message => "already exists"
end

These entries will give automatic checking such as −

    vapdates_length_of − The field is not blank and not too long.

    vapdates_uniqueness_of − Duppcate values are trapped. Instead of the default Rails error message, we have given our custom message.

Here we are trying to provide a bigger title while editing the exiting record. It produces the following error message, just because we have added the above vapdations −

Added Error

How Scaffolding is Different?

If you have gone through the previous chapters, then you must have seen that we had created methods to pst, show, delete, and create data, but scaffolding does that job automatically.

Advertisements