《Rails 5 敏捷开发》学习笔记 - 第6章 任务A:创建应用程序

本章介绍了如何迭代地创建并优化一个用来维护商品信息(包括:创建新商品、编辑现有商品、删除不再需要的商品等功能)的小型应用程序。

6.1 创建一个维护商品的应用程序

第1步:创建一个新的Rails应用程序
在指定目录(如:work目录)下,创建一个新的Rails应用程序,并将其命名为“depot”,命令如下:

work>​​ ​​rails​​ ​​new​​ ​​depot​

第2步:创建数据库
实际上,SQLite3是Rails默认的数据库,在创建好Rails应用程序后,也就自动创建好了一个SQLite3数据库。所以,如果不打算使用其他类型的数据库,就可以跳过这一步。

第3步:生成脚手架
要实现创建、展示、编辑、删除商品等功能,就需要创建一个数据库表和Rails模型,应用程序将通过这个模型,来使用这个数据库表和一系列创建用户界面的视图以及协调应用程序的控制器。

在Rails中,通过生成一个指定模型的脚手架(scaffold),便可以同时创建好模型、视图、控制器和迁移(在迁移文件中将自动创建数据库表)。命令如下:

depot>​​ rails​​ ​​generate​​ ​​scaffold​​ ​​Product​​ ​​\​
​​title:string​​ ​​description:text​​ ​​image_url:string​​ ​​price:decimal​

  • 首先,需要切换到应用程序depot目录下来执行该命令。
  • 这条命令中,Product是我们自己定义的一个模型名称,模型名称需要使用单数形式,因为要让该模型自动映射到后续生成的products表。(在Rails中,如果表名是模型名称的复数形式,那么该模型会自动映射到这张表。)
  • 执行这条命令后,首先会创建一个迁移文件,文件位于:db/migrate目录中。一次迁移代表着将对数据进行一次修改,这些修改既可以更新数据库模式,也可以更新数据库中的数据。在这个迁移文件中,会自动生成一个方法,用来在数据库中创建一个名叫products的表。模型Product将自动映射到这个products表。
  • 随后,会生成模型文件(位于:app/models/product.rb)、控制器文件(位于:app/controllers/product_controller.rb)和一些视图文件(位于:app/views/products目录下)。
  • 命令的第2行,是在定义products这个数据库表中的每个属性的数据类型。

第4步:应用迁移
生成迁移文件后,这些迁移(或者说对数据的修改)还并没有应用到数据库中去。所以,其实目前还没有生成products这个数据库表。

应用迁移的命令如下:

depot> rake db:migrate

rake命令会去搜索所有尚未应用到数据库中的迁移,并将这些迁移应用到开发数据库中去。

第5步:启动Rails服务,访问Rails应用程序
启动Rails提供的本地服务器的命令如下:

depot> rails server

该命令会默认使用端口3000来启动本地服务器。如果访问localhost:3000,浏览器将显示RAILS的欢迎页面。如果要查看本例的商品清单页面,需要在URL中包含端口号3000和小写的控制器名products,即访问localhost:3000/products 。

第6步:进行简单的测试
使用命令:depot> rake test 可以对这个depot应用程序进行简单的测试,这是Rails根据脚手架生成的一些简单的单元、功能和集成测试。


6.2 美化商品清单

第1步:创建一些演示用的测试数据
为了在每一次进行演示时,页面展示的都是同样的测试数据,我们可以将title、description、image_url、price等测试数据写入seeds.rb文件中,它位于db目录下。

# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
#   movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
#   Character.create(name: 'Luke', movie: movies.first)

#---
# Excerpted from "Agile Web Development with Rails 5",
# published by The Pragmatic Bookshelf.
# Copyrights apply to this code. It may not be used to create training material,
# courses, books, articles, and the like. Contact us if you are in doubt.
# We make no guarantees that this code is fit for any purpose.
# Visit http://www.pragmaticprogrammer.com/titles/rails5 for more book information.
#---
# encoding: utf-8
Product.delete_all
Product.create!(title: 'Rails, Angular, Postgres, and Bootstrap',
  description:
    %{<p>
      <em>Powerful, Effective, and Efficient Full-Stack Web Development</em>
      As a Rails developer, you care about user experience and performance,
      but you also want simple and maintainable code. Achieve all that by
      embracing the full stack of web development, from styling with
      Bootstrap, building an interactive user interface with AngularJS, to
      storing data quickly and reliably in PostgreSQL. Take a holistic view of
      full-stack development to create usable, high-performing applications,
      and learn to use these technologies effectively in a Ruby on Rails
      environment.
      </p>},
  image_url: 'dcbang.jpg',    
  price: 45.00)
# . . .
Product.create!(title: 'Seven Mobile Apps in Seven Weeks',
  description:
    %{<p>
      <em>Native Apps, Multiple Platforms</em>
      Answer the question “Can we build this for ALL the devices?” with a
      resounding YES. This book will help you get there with a real-world
      introduction to seven platforms, whether you’re new to mobile or an
      experienced developer needing to expand your options. Plus, you’ll find
      out which cross-platform solution makes the most sense for your needs.
      </p>},
  image_url: '7apps.jpg',
  price: 26.00)
# . . .

Product.create!(title: 'Ruby Performance Optimization',
  description:
    %{<p>
      <em>Why Ruby Is Slow, and How to Fix It</em> 
      You don’t have to accept slow Ruby or Rails performance. In this
      comprehensive guide to Ruby optimization, you’ll learn how to write
      faster Ruby code—but that’s just the beginning. See exactly what makes
      Ruby and Rails code slow, and how to fix it. Alex Dymo will guide you
      through perils of memory and CPU optimization, profiling, measuring,
      performance testing, garbage collection, and tuning. You’ll find that
      all those “hard” things aren’t so difficult after all, and your code
      will run orders of magnitude faster.
      </p>},
  image_url: 'adrpo.jpg',
  price: 46.00)

注意:这个seed.rb脚本文件在加载新数据前,将从products表中移除现有的数据。请谨慎操作!

然后,执行命令:

depot> rails db:seed

刷新页面,可以看到加到seeds.rb文件里去的内容就显示在了页面上。

第2步:添加样式
用脚手架生成器生成一个脚手架后,会存在一个名为products.scss的空白样式表文件,它是用来存放和Products控制器相关的所有样式。这个文件位于app/assets/stylesheets目录下。所以,我们把样式添加进这个.scss文件中去。

// Place all the styles related to the Products controller here.
// They will automatically be included in application.css.
// You can use Sass (SCSS) here: http://sass-lang.com/

    .products {
      table {
            border-collapse: collapse;
          }

      table tr td {
            padding: 5px;
            vertical-align: top;
          }

      .list_image {
            width:  60px;
            height: 70px;
          }

      .list_description {
            width: 60%;

            dl {
              margin: 0;
            }

            dt {
              color:        #244;
              font-weight:  bold;
              font-size:    larger;
            }

            dd {
                      margin: 0;
            }
          }

      .list_actions {
            font-size:    x-small;
            text-align:   right;
            padding-left: 1em;
          }

      .list_line_even {
            background:   #e0f8f8;
          }

      .list_line_odd {
            background:   #f8b0f8;
          }
    }

SCSS只是提供了额外的语法,让样式表更容易编写和维护,它并不会和标准的CSS发生冲突,浏览器也会将SCSS转换成它自己能理解的CSS。

第3步:设置用于使用该样式表的class属性
app/views/layouts目录下,有一个application.html.erb文件。它是Rails应用程序的页面布局文件,它会为整个Rails应用程序生成一个标准的页面环境。

在这个文件的body元素中,添加一个class属性,让它去使用刚才那个和Products控制器相关的样式表。

<!DOCTYPE html>
<html>
  <head>
    <title>Depot</title>
    <%= csrf_meta_tags %>

    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
  </head>

  <body class='<%= controller.controller_name %>'>
    <%= yield %>
  </body>
</html>

因为Rails会一次性加载所有的样式表,所以这里我们将class属性的值设为了“<%= controller.controller_name %>”,加之当前只有一个控制器Products,所以这样做可以让它只使用和Products控制器相关的样式表。

第4步:查看样式表的效果
刷新页面,便已经可以看到上述样式表起到的效果了。

第5步:对products页面的布局进行微调
可以对脚手架生成器自动生成的app/views/products/index.html.erb文件的内容进行修改,从而实现对products页面布局的微调。

<p id="notice"><%= notice %></p>

<h1>Products</h1>

<table>
  <!--<thead>-->
    <!--<tr>-->
      <!--<th>Title</th>-->
      <!--<th>Description</th>-->
      <!--<th>Image url</th>-->
      <!--<th>Price</th>-->
      <!--<th colspan="3"></th>-->
    <!--</tr>-->
  <!--</thead>-->

  <!--<tbody>-->
    <% @products.each do |product| %>
      <tr class="<%= cycle('list_line_odd', 'list_line_even') %>">
        <td><%= image_tag(product.image_url, class:'list_image') %></td>
        <td class="list_description">
          <dl>
            <dt><%= product.title %></dt>
            <dd><%= truncate(strip_tags(product.description), length: 80) %></dd>
          </dl>
        </td>
        <!--<td><%= product.price %>-->
        <td class="list_actions">
          <%= link_to 'Show', product %><br>
          <%= link_to 'Edit', edit_product_path(product) %><br>
          <%= link_to 'Destroy', product, method: :delete, data: { confirm: 'Are you sure?' } %>
        </td>
      </tr>
    <% end %>
  <!--</tbody>-->
</table>

<br>

<%= link_to 'New Product', new_product_path %>

这段代码中会去调用具体的图片文件,而这些图片需要被放到app/assets/images目录下。

猜你喜欢

转载自blog.csdn.net/heming87/article/details/82532150
今日推荐