Ruby on Rails 2.1 - 脚手架



在开发 Rails 应用程序时,特别是那些主要提供数据库中数据简单界面的应用程序,使用脚手架方法通常很有用。

脚手架提供的不仅仅是廉价的演示效果。它还有一些好处:

  • 您可以快速向用户提供代码以获取反馈。

  • 您可以通过更快的成功获得动力。

  • 您可以通过查看生成的代码来学习 Rails 的工作原理。

  • 您可以使用脚手架作为基础来启动您的开发。

脚手架示例

Ruby on Rails 2.0 改变了 Rails 使用脚手架的方式。为了理解脚手架,让我们创建一个名为cookbook的数据库和一个名为recipes的表。

创建空的 Rails Web 应用程序

打开命令窗口并导航到您要创建此cookbook Web 应用程序的位置。我们使用了 c:\ruby。运行以下命令以创建完整的目录结构和所需的.yml文件 MySQL 数据库。

C:\ruby> rails -d mysql cookbook

在这里,我们使用-d mysql选项来指定我们希望使用 MySQL 数据库。我们可以使用-d选项指定任何其他数据库名称,例如oraclepostgress。默认情况下,Rails 使用SQLite数据库。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

设置数据库

以下是创建数据库的方法:

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)

为了指示 Rails 找到数据库,请编辑配置文件 ~\cookbook\config\database.yml 并将数据库名称更改为 cookbook。完成后,它应如下所示:

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

注意 - 如果您想使用 MySQL 之外的任何其他数据库,则可以使用类似的设置来配置其他数据库适配器。

Rails 允许您在开发模式、测试模式或生产模式下运行,使用不同的数据库。此应用程序对每个模式都使用相同的数据库。

数据库表定义

假设我们的recipes表具有以下结构:

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

生成的脚手架代码

使用scaffold操作,Rails 会动态生成它所需的所有代码。通过运行scaffold作为脚本,生成模型以及脚手架,以及所需的数据库迁移脚本,以及控制器、帮助程序和测试支持文件,如下所示:

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

注意使用单数名称Recipe来创建复数表名recipes。但是,上述命令将生成以下消息:

   exists  app/models/
   exists  app/controllers/
   exists  app/helpers/
   create  app/views/recipes
   exists  app/views/layouts/
   exists  test/functional/
   exists  test/unit/
   exists  public/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  public/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>

现在,让我们检查一下幕后发生了什么。

控制器

让我们看看控制器背后的代码。此代码由scaffold生成器生成。如果您打开 app/controllers/recipes_controller.rb,您会发现如下内容:

class RecipesController < ApplicationController
   # 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

此文件自动实现了所有方法。您可以使用这些可用方法执行任何创建、读取、删除或编辑操作。

当 Rails 应用程序的用户选择一个操作,例如“显示” - 控制器将执行相应部分中的任何代码 - “def show” - 然后默认情况下将呈现相同名称的模板 - “show.html.erb”。此默认行为可以通过覆盖任何模板中的代码来覆盖。

控制器使用 ActiveRecord 方法,例如find、find_all、new、save、update_attributes 和 destroy来将数据移动到数据库表和从数据库表移动数据。请注意,您不必编写任何 SQL 语句,Rails 会自动处理。

视图

所有视图和相应的控制器方法都是由scaffold命令创建的,它们位于 app/views/recipes 目录中。您将在该目录中找到以下文件:

  • index.html.erb - 这是显示默认页面的模板文件,当您键入 http://127.0.0.1:3000/recipes 时将执行。

  • new.html.erb - 这是创建新食谱的模板,每当您尝试创建新食谱时都会执行。

  • show.html.erb - 这是显示数据库中所有食谱的模板,每当您尝试查看所有食谱时都会执行。

  • edit.html.erb - 这是编辑数据库中任何食谱的模板,每当您尝试编辑任何食谱时都会执行。

我们建议您逐个打开这些文件并尝试理解它们的源代码。

迁移

您会在~/cookbook/db/migrate子目录中找到一个迁移文件。此文件将具有以下内容:

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

要创建数据库中所需的文件,请使用以下辅助脚本。

cookbook> rake db:migrate

此命令将在您的cookbook数据库中创建recipesschema_migrations表。在继续之前,请确保您已在数据库中成功创建了所需的表。

准备测试

上述所有步骤都使您的数据库表生动起来。它为您的数据提供了一个简单的界面,以及以下方法:

  • 创建新条目
  • 编辑当前条目
  • 查看当前条目
  • 销毁当前条目

在创建或编辑条目时,脚手架将完成表单生成和处理的所有繁重工作。它甚至会提供智能表单生成,支持以下类型的输入:

  • 简单的文本字符串
  • 文本区域(或大块文本)
  • 日期选择器
  • 日期时间选择器

现在,转到 cookbook 目录并使用以下命令运行 Web 服务器:

cookbook> ruby script/server

现在,打开浏览器并导航到 http://127.0.0.1:3000/recipes/new。它将提供一个屏幕,用于在 recipes 表中创建新条目。屏幕截图如下所示:

Create Recipe

现在,在给定的文本框中输入一些值,然后按“创建”按钮以创建新的食谱。您的记录将添加到 recipes 表中,并将显示以下结果:

Added Recipe

您可以使用编辑选项来编辑食谱,或者使用返回按钮返回上一页。假设您按下了返回按钮,它将显示数据库中所有可用的食谱。由于我们的数据库中只有一条记录,它将显示以下屏幕:

Back Recipe

此屏幕使您可以查看食谱表的完整详细信息。此外,它还提供编辑甚至删除表的选项。

增强模型

Rails 免费为您提供了大量的错误处理。为了理解这一点,请向空的食谱模型添加一些验证规则:

修改~/cookbook/app/models/recipe.rb如下,然后测试您的应用程序:

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

这些条目将提供自动检查,例如:

  • validates_length_of - 字段不为空且不超过长度限制。

  • validates_uniqueness_of - 重复值会被捕获。我们给出了自定义消息,而不是默认的 Rails 错误消息。

在这里,我们尝试在编辑现有记录时提供一个更长的标题。由于我们添加了上述验证,因此会产生以下错误消息:

Added Error

脚手架有何不同?

如果您阅读了前面的章节,那么您一定已经看到我们创建了列出、显示、删除和创建数据的方法,但是脚手架会自动完成这项工作。

广告