Ruby on Rails - 脚手架

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

脚手架提供的不仅仅是廉价的演示刺激。以下是一些好处 −

  • 您可以快速将代码呈现给用户以获得反馈。

  • 更快的成功会激励您。

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

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

脚手架示例

为了理解脚手架,让我们创建一个名为cookbook的数据库和一个名为recipes的表。

创建一个空的 Rails Web 应用程序

打开命令窗口并导航到您想要创建此cookbook Web 应用程序的位置。因此,运行以下命令来创建完整的目录结构。

tp> rails new cookbook

设置数据库

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

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

mysql> grant all permission on cookbook.*
to 'root'@'localhost' established by 'password';
Query OK, 0 rows impacted (0.00 sec)

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

要指示 Rails 如何查找数据库,请编辑配置文件 cookbook\config\database.yml 并将数据库名称更改为 cookbook。将密码留空。完成后应如下所示 −

development:
   adapter: mysql
   database: cookbook
   username: root
   password: [password]
   host: localhost
	
test:
   adapter: mysql
   database: cookbook
   username: root
   password: [password]
   host: localhost
	
production:
   adapter: mysql
   database: cookbook
   username: root
   password: [password]
   host: localhost

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

生成的脚手架代码

使用脚手架操作,Rails 会动态生成所需的所有代码。通过将 scaffold 作为脚本运行,我们可以将所有代码写入磁盘,在那里我们可以对其进行调查,然后开始根据我们的要求进行调整。

现在,让我们再次开始使用脚手架帮助脚本 − 手动生成脚手架代码

cookbook> rails generate scaffold recipe

它会生成如下所示的自动文件 −

Scaffold

控制器

让我们看看控制器背后的代码。此代码由 scaffold 生成器生成。如果您打开 app/controllers/recipes_controller.rb,那么您将找到以下内容 −

class RecipesController < ApplicationController
   before_action :set_recipe, only: [:show, :edit, :update, :destroy]
   
   # GET /recipes
   # GET /recipes.json
   def index
      @recipes = Recipe.all
   end
   
   # GET /recipes/1
   # GET /recipes/1.json
   def show
   end
   
   # GET /recipes/new
   def new
      @recipe = Recipe.new
   end
   
   # GET /recipes/1/edit
   def edit
   end
   
   # POST /recipes
   # POST /recipes.json
   def create
      @recipe = Recipe.new(recipe_params)
      
      respond_to do |format|
         if @recipe.save
            format.html { redirect_to @recipe, notice: 'Recipe was successfully created.' }
            format.json { render :show, status: :created, location: @recipe }
         else
            format.html { render :new }
            format.json { render json: @recipe.errors, status: :unprocessable_entity }
         end
      end
      
   end
   
   # PATCH/PUT /recipes/1
   # PATCH/PUT /recipes/1.json
   def update
      respond_to do |format|
         if @recipe.update(recipe_params)
            format.html { redirect_to @recipe, notice: 'Recipe was successfully updated.' }
            format.json { render :show, status: :ok, location: @recipe }
         else
            format.html { render :edit }
            format.json { render json: @recipe.errors, status: :unprocessable_entity }
         end
      end
      
   end
   
   # DELETE /recipes/1
   # DELETE /recipes/1.json
   def destroy
      @recipe.destroy
         respond_to do |format|
         format.html { redirect_to recipes_url, notice: 'Recipe was successfully destroyed.' }
         format.json { head :no_content }
      end
   end
   
   private
   
   # 使用回调来共享操作之间的常见设置或约束。
   def set_recipe
      @recipe = Recipe.find(params[:id])
   end
   
   # 永远不要相信来自可怕的互联网的参数,只允许白名单通过。
   def recipe_params
      params.require(:recipe).permit(:tittle, :instructions)
   end
end

当 Rails 应用程序的用户选择一项操作(例如"Show")时,控制器将执行相应部分中的任何代码 - "def show",然后默认呈现同名模板 - "show.html.erb"。此默认行为可以被覆盖。

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

这一行代码将使数据库表变得生动。它将为您的数据提供一个简单的界面,以及−

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

在创建或编辑条目时,scaffold 将为您完成所有繁重的工作,例如表单生成和处理,甚至提供巧妙的表单生成,支持以下类型的输入−

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

您可以使用 Rails Migrations 来创建和维护表格。

rake db:migrate RAILS_ENV=development

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

cookbook> rails server

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

创建食谱

按下 创建 按钮创建新食谱后,您的记录将添加到食谱表中,并显示以下结果 −

创建食谱

您可以看到编辑、显示和销毁记录的选项。因此,请尝试使用这些选项。

您还可以使用 URL http://127.0.0.1:3000/recipe/list 列出食谱表中可用的所有食谱。

增强模型

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

按如下方式修改 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 错误消息。

创建脚手架的替代方法

创建一个如上所示的应用程序,生成的脚手架代码如下所示

rails g scaffold Recipe tittle:string instructions:text

上面的代码使用带有标题和说明列的 sqlite3 生成带有数据库的自动文件,如下图所示。

Scaffold

我们需要使用以下语法迁移数据库。

$ rake db:migrate RAILS_ENV=development

最后使用以下命令运行应用程序命令行 −

rails server

它将生成如上图所示的结果。

视图

所有视图和相应的所有控制器方法均由 scaffold 命令创建,它们位于 app/views/recipes 目录中。

脚手架有何不同?

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