欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Ruby On Rails的第一个应用(一)--创建应用程序

程序员文章站 2022-03-03 08:11:23
...

   以下所有内容都依据《Agile Web Development with Rails Fourth Edition》。使用增量式开发来完成一个实例,以熟悉ROR的开发。整个过程通过完成一系列任务来实现。以下用小迭代的形式来开发整个实例。

 

I 任务A:创建应用程序

 

一、迭代A1:创建商品维护的应用程序

 

1.创建rails应用程序

e: #打开dos终端,进入E盘符

cd E:\works\ruby #cd到工作目录下

rails new depot (可以加--skip-bundle参数 #新建一个应用程序depot。--skip-bundle意思是跳过检测安装bundle。)

 

E:\works\ruby>rails new depot
      create
      create  README.rdoc
      create  Rakefile
      create  config.ru
      create  .gitignore
      create  Gemfile
      create  app
      create  app/assets/images/rails.png
      create  app/assets/javascripts/application.js
      create  app/assets/stylesheets/application.css
      create  app/controllers/application_controller.rb
      create  app/helpers/application_helper.rb
      create  app/mailers
      create  app/models
      create  app/views/layouts/application.html.erb
      create  app/mailers/.gitkeep
      create  app/models/.gitkeep
      create  config
      create  config/routes.rb
      create  config/application.rb
      create  config/environment.rb
      create  config/environments
      create  config/environments/development.rb
      create  config/environments/production.rb
      create  config/environments/test.rb
      create  config/initializers
      create  config/initializers/backtrace_silencers.rb
      create  config/initializers/inflections.rb
      create  config/initializers/mime_types.rb
      create  config/initializers/secret_token.rb
      create  config/initializers/session_store.rb
      create  config/initializers/wrap_parameters.rb
      create  config/locales
      create  config/locales/en.yml
      create  config/boot.rb
      create  config/database.yml
      create  db
      create  db/seeds.rb
      create  doc
      create  doc/README_FOR_APP
      create  lib
      create  lib/tasks
      create  lib/tasks/.gitkeep
      create  lib/assets
      create  lib/assets/.gitkeep
      create  log
      create  log/.gitkeep
      create  public
      create  public/404.html
      create  public/422.html
      create  public/500.html
      create  public/favicon.ico
      create  public/index.html
      create  public/robots.txt
      create  script
      create  script/rails
      create  test/fixtures
      create  test/fixtures/.gitkeep
      create  test/functional
      create  test/functional/.gitkeep
      create  test/integration
      create  test/integration/.gitkeep
      create  test/unit
      create  test/unit/.gitkeep
      create  test/performance/browsing_test.rb
      create  test/test_helper.rb
      create  tmp/cache
      create  tmp/cache/assets
      create  vendor/assets/javascripts
      create  vendor/assets/javascripts/.gitkeep
      create  vendor/assets/stylesheets
      create  vendor/assets/stylesheets/.gitkeep
      create  vendor/plugins
      create  vendor/plugins/.gitkeep
         run  bundle install
Fetching source index for https://rubygems.org/
Using rake (10.0.3)
Using i18n (0.6.4)
Using multi_json (1.6.1)
Using activesupport (3.2.1)
Using builder (3.0.4)
Using activemodel (3.2.1)
Using erubis (2.7.0)
Using journey (1.0.4)
Using rack (1.4.5)
Using rack-cache (1.2)
Using rack-test (0.6.2)
Using hike (1.2.1)
Using tilt (1.3.5)
Using sprockets (2.1.3)
Using actionpack (3.2.1)
Using mime-types (1.21)
Using polyglot (0.3.3)
Using treetop (1.4.12)
Using mail (2.4.4)
Using actionmailer (3.2.1)
Using arel (3.0.2)
Using tzinfo (0.3.37)
Using activerecord (3.2.1)
Using activeresource (3.2.1)
Using bundler (1.0.22)
Using coffee-script-source (1.6.1)
Using execjs (1.4.0)
Using coffee-script (2.2.0)
Using rack-ssl (1.3.3)
Using json (1.7.7)
Using rdoc (3.12.2)
Using thor (0.14.6)
Using railties (3.2.1)
Using coffee-rails (3.2.2)
Using jquery-rails (2.2.1)
Using rails (3.2.1)
Using sass (3.2.7)
Using sass-rails (3.2.6)
Using sqlite3 (1.3.7)
Using uglifier (1.3.0)
Your bundle is complete! Use `bundle show [gemname]` to see where a bundled gem
is installed.
 

 

cd depot #进入应用程序主目录以下称根目录或者目录中用/开头表示此目录下

 

2.创建数据库

这里使用rails的默认数据库SQLite3。它会随rails一起安装。

 

3.生成脚手架(scaffold)

首先我们需要实现Products表,现在在数据库中实现它。需要创建数据库表和rails模型,应用程序通过这个模型使用该表、一系列创建用户界面的视图以及协调应用程序的控制器。现在为products表创建模型、视图、控制器和迁移,即执行以下命令生成脚手架:

rails generate scaffold Product ^

  title:string description:text image_url:string price:decimal

此命令过长要多行输入windows下用^连接下一行输入。unix下用\。命令行中使用的是单数形式的product,也就是模型,rails中会自动映射到数据库表products

生成了一批文件,包括迁移文件:"时间戳(一串数字如:20130312000001)_create_products.rb";product模型;商品控制器;部分视图

#执行此命令出现了警告先忽略

 

E:\works\ruby\depot>rails generate scaffold Product ^
   title:string description:text image_url:string price:decimal
        SECURITY WARNING: No secret option provided to Rack::Session::Cookie.
        This poses a security threat. It is strongly recommended that you
        provide a secret to prevent exploits that may be possible from crafted
        cookies. This will not be supported in future versions of Rack, and
        future versions will even invalidate your existing user cookies.

        Called from: D:/dev/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/ac
tionpack-3.2.1/lib/action_dispatch/middleware/session/abstract_store.rb:28:in `i
nitialize'.

      invoke  active_record
      create    db/migrate/20130314064527_create_products.rb
      create    app/models/product.rb
      invoke    test_unit
      create      test/unit/product_test.rb
      create      test/fixtures/products.yml
       route  resources :products
      invoke  scaffold_controller
      create    app/controllers/products_controller.rb
      invoke    erb
      create      app/views/products
      create      app/views/products/index.html.erb
      create      app/views/products/edit.html.erb
      create      app/views/products/show.html.erb
      create      app/views/products/new.html.erb
      create      app/views/products/_form.html.erb
      invoke    test_unit
      create      test/functional/products_controller_test.rb
      invoke    helper
      create      app/helpers/products_helper.rb
      invoke      test_unit
      create        test/unit/helpers/products_helper_test.rb
      invoke  assets
      invoke    coffee
      create      app/assets/javascripts/products.js.coffee
      invoke    scss
      create      app/assets/stylesheets/products.css.scss
      invoke  scss
      create    app/assets/stylesheets/scaffolds.css.scss
 

 

 

4.应用迁移

虽然生成脚手架时已经告诉rails每个属性的基本数据类型,但是还要完善价格的定义,如:共8位有效数,小数点后保留两位。

打开/db/migrate/时间戳_create_products.rb,修改第7行,末尾添加", :precision => 8, :scale =>2"。

 

class CreateProducts < ActiveRecord::Migration
  def change
    create_table :products do |t|
      t.string :title
      t.text :description
      t.string :image_url
      t.decimal :price, precision: 8, scale: 2

      t.timestamps
    end
  end
end
 

 

然后执行迁移:

rake db:migrate

此命令将所有尚未执行的迁移应用到数据库中。这里表products添加到了数据库中,database.yml文件的development部分定义了这个数据库

 

E:\works\ruby\depot>rake db:migrate
==  CreateProducts: migrating =================================================
-- create_table(:products)
   -> 0.0156s
==  CreateProducts: migrated (0.0156s) ========================================
 

 

 

5.查看商品清单

rails server

启动rails提供的本地服务器。默认端口是3000,如果看到Address already in use之类错误,是另外已经启动了rails服务器。启动服务后提示ctrl+c可以关闭服务,不过我试了多次都未果,不行就直接叉掉终端吧。

启动成功:

 

E:\works\ruby\depot>rails server
=> Booting WEBrick
=> Rails 3.2.1 application starting in development on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
        SECURITY WARNING: No secret option provided to Rack::Session::Cookie.
        This poses a security threat. It is strongly recommended that you
        provide a secret to prevent exploits that may be possible from crafted
        cookies. This will not be supported in future versions of Rack, and
        future versions will even invalidate your existing user cookies.

        Called from: D:/dev/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/ac
tionpack-3.2.1/lib/action_dispatch/middleware/session/abstract_store.rb:28:in `i
nitialize'.

[2013-03-14 14:52:38] INFO  WEBrick 1.3.1
[2013-03-14 14:52:38] INFO  ruby 1.9.3 (2012-02-16) [i386-mingw32]
[2013-03-14 14:52:38] INFO  WEBrick::HTTPServer#start: pid=13348 port=3000
 

 

访问地址http://localhost:3000/products查看效果,在里面可以添加、查看、编辑、删除商品。

在此我们也该知道一个命令:

rake test #此命令运行完后应该可以看到两行信息0 failures 和 0 errors

 

E:\works\ruby\depot>rake test
        SECURITY WARNING: No secret option provided to Rack::Session::Cookie.
        This poses a security threat. It is strongly recommended that you
        provide a secret to prevent exploits that may be possible from crafted
        cookies. This will not be supported in future versions of Rack, and
        future versions will even invalidate your existing user cookies.

        Called from: D:/dev/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/ac
tionpack-3.2.1/lib/action_dispatch/middleware/session/abstract_store.rb:28:in `i
nitialize'.

Rack::File headers parameter replaces cache_control after Rack 1.5.
Run options:

# Running tests:



Finished tests in 0.015625s, 0.0000 tests/s, 0.0000 assertions/s.

0 tests, 0 assertions, 0 failures, 0 errors, 0 skips
        SECURITY WARNING: No secret option provided to Rack::Session::Cookie.
        This poses a security threat. It is strongly recommended that you
        provide a secret to prevent exploits that may be possible from crafted
        cookies. This will not be supported in future versions of Rack, and
        future versions will even invalidate your existing user cookies.

        Called from: D:/dev/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/ac
tionpack-3.2.1/lib/action_dispatch/middleware/session/abstract_store.rb:28:in `i
nitialize'.

Rack::File headers parameter replaces cache_control after Rack 1.5.
Run options:

# Running tests:

.......

Finished tests in 0.781250s, 8.9600 tests/s, 12.8000 assertions/s.

7 tests, 10 assertions, 0 failures, 0 errors, 0 skips
  

 

二、迭代A2:美化商品清单

首先下载源代码,地址:http://pragprog.com/titles/rails4/source_code或者http://download.csdn.net/download/loveanna7/5133666

然后下载depot.css:http://media.pragprog.com/titles/rails4/code/rails30/depot_b/public/stylesheets/depot.css(因为我在depot_b没有发现在depot.css)

depot.css代码:

 

/* Global styles */

#store #notice {
        color: #000;
        border: 2px solid red;
        padding: 1em;
        margin-bottom: 2em;
        background-color: #f0f0f0;
        font: bold smaller sans-serif;
}


#store h1 {
        font:  150% sans-serif;
        color: #226;
        border-bottom: 3px dotted #77d;
}

/* Styles for products/index */

#product_list table {
        border-collapse: collapse;
}

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

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

#product_list .list_description {
  width:        60%;
}

#product_list .list_description dl {
        margin: 0;
}

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

#product_list .list_description dd {
        margin: 0;
}

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

#product_list .list_line_even {
  background:   #e0f8f8;
}

#product_list .list_line_odd {
  background:   #f8b0f8;
}

/* An entry in the store catalog */

#store  .entry {
  overflow: auto;
  margin-top: 1em;
  border-bottom: 1px dotted #77d;
}

#store  .title {
  font-size: 120%;
  font-family: sans-serif;
}

#store .entry img {
  width: 80px;
  margin-right: 5px;
  margin-bottom: 5px;
  float: left;
}


#store .entry h3 {
 margin-top: 0;
 margin-bottom: 2px;
 color: #227;
}

#store .entry p {
 margin-top: 0.5em; 
 margin-bottom: 0.8em; 
}

#store .entry .price_line {
 clear: both;
 margin-bottom: 0.5em;
}

#store .entry .add_to_cart {
  position: relative;
}

#store .entry  .price {
  color: #44a;
  font-weight: bold;
  margin-right: 2em;
}
 

 

1.现在希望有一组一致的测试数据,我们可以从脚手架生成的接口中添加数据,但是以后其他开发人员我们的代码库的基础工作时,又要重新做。rails中可以通过导入种子数据。

修改/db/seeds.rb文件,这里可以从源码中depot_b/db/seeds.rb拷贝过来。

# encoding: utf-8
Product.delete_all
Product.create(title: 'CoffeeScript',
  description: 
    %{<p>
        CoffeeScript is JavaScript done right. It provides all of JavaScript's
	functionality wrapped in a cleaner, more succinct syntax. In the first
	book on this exciting new language, CoffeeScript guru Trevor Burnham
	shows you how to hold onto all the power and flexibility of JavaScript
	while writing clearer, cleaner, and safer code.
      </p>},
  image_url:   'cs.jpg',    
  price: 36.00)
# . . .
Product.create(title: 'Programming Ruby 1.9 & 2.0',
  description:
    %{<p>
        Ruby is the fastest growing and most exciting dynamic language
        out there. If you need to get working programs delivered fast,
        you should add Ruby to your toolbox.
      </p>},
  image_url: 'ruby.jpg',
  price: 49.95)
# . . .

Product.create(title: 'Rails Test Prescriptions',
  description: 
    %{<p>
        <em>Rails Test Prescriptions</em> is a comprehensive guide to testing
        Rails applications, covering Test-Driven Development from both a
        theoretical perspective (why to test) and from a practical perspective
        (how to test effectively). It covers the core Rails testing tools and
        procedures for Rails 2 and Rails 3, and introduces popular add-ons,
        including Cucumber, Shoulda, Machinist, Mocha, and Rcov.
      </p>},
  image_url: 'rtp.jpg',
  price: 34.95)

 

接下来拷贝图片:从depot_b/app/assets/images目录copy到我们的/app/assets/images下。

rails.png:

Ruby On Rails的第一个应用(一)--创建应用程序
            
    
    博客分类: ruby on rails Ruby On Rails的第一个应用程序depotrailsrorRubyOnRails

ruby.jpg

Ruby On Rails的第一个应用(一)--创建应用程序
            
    
    博客分类: ruby on rails Ruby On Rails的第一个应用程序depotrailsrorRubyOnRails

logo.png

Ruby On Rails的第一个应用(一)--创建应用程序
            
    
    博客分类: ruby on rails Ruby On Rails的第一个应用程序depotrailsrorRubyOnRails

rtp.jpg

Ruby On Rails的第一个应用(一)--创建应用程序
            
    
    博客分类: ruby on rails Ruby On Rails的第一个应用程序depotrailsrorRubyOnRails

cs.jpg

Ruby On Rails的第一个应用(一)--创建应用程序
            
    
    博客分类: ruby on rails Ruby On Rails的第一个应用程序depotrailsrorRubyOnRails

然后把下载的depot.css复制到/app/assets/stylesheets下

据书上说脚手架生成的应用程序都使用目录/public/stylesheets/scaffold.css,但是我找不到此文件。却在/app/assets/stylesheets发现在scaffold.css.scss。depot.css要放到此相同的目录下,这里放到/app/assets/stylesheets,接下来证明我放的是对的,估计是版本的问题。在此我的理解是我们要把资源库文件都放到/app/assets目录下。我们会发现在这个目录下有三个文件夹,images、javascripts、stylesheets,怎么放你懂的。

到现在我们可能会想,我们把文件拷贝进去了,应用程序是如何加载这些的呢?如果在.html.erb文件(就像jsp/php/asp文件),找不到引用,head都看不到;这是因为rails有一个单独的文件来为整个应用程序创建标准的页面环境,这个文件是/app/views/layouts/application.html.erb。这里没有做任何改动,它加载了所有的assets文件夹下的内容了(一会我们验证)。

2.rake db:seed

3.编辑/app/views/products/index.html.erb来替换由脚手架生成的视图。内容改为:

<div id=product_list>

<h1>Listing products</h1>

 

<table>


<% @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 class="list_actions">

    <%= link_to 'Show', product %><br/>

    <%= link_to 'Edit', edit_product_path(product) %><br/>

    <%= link_to 'Destroy', product, confirm: 'Are you sure?', method: :delete %></td>

  </tr>

<% end %>

 

</div>

</table>

 

<br />

 

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

 

4.重新访问地址http://localhost:3000/products查看效果。

Ruby On Rails的第一个应用(一)--创建应用程序
            
    
    博客分类: ruby on rails Ruby On Rails的第一个应用程序depotrailsrorRubyOnRails

再查看源代码你会发现一些东西:加载的样式表路径如/assets/depot.css?body=1、图片路径如/assets/cs.jpg。

即如图片:在seed.rb中用的是cs.jpg,前面没有带任何目录名;cs.jpg对应的文件放在/app/assets/images/目录下;访问的路径是/assets/cs.jpg。