`
jarry-li
  • 浏览: 43534 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

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

阅读更多

   以下所有内容都依据《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:

rails.png

ruby.jpg

ruby.jpg

logo.png

logo.png

rtp.jpg

rtp.jpg

cs.jpg

cs.jpg

然后把下载的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查看效果。

products list

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

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

 

 

1
0
分享到:
评论

相关推荐

    ruby on rails 101

    - **周二**:创建第一个应用程序,学习如何处理文件、生成器和脚本。 - **周三**:掌握迁移、ActiveRecord、ActionController和ActionView的基本用法。 - **周四**:深入了解ActiveRecord的关联、验证和回调机制;...

    ruby on rails最新版

    Ruby on Rails,简称Rails,是基于Ruby编程语言的一个开源Web应用程序框架,它遵循MVC(模型-视图-控制器)架构模式,旨在提高开发效率和代码的可读性。Rails以其“约定优于配置”(Convention over Configuration)...

    Ruby on Rails Tutorial

    在这个全球互联的世界中,计算机编程和 Web 应用程序开发都在迅猛发展,我很期待能为中国的开发者提供 Ruby on Rails 培训。学习英语这门世界语言是很重要的,但先通过母语学习往往会更有效果。正因为这样,当看到 ...

    Ruby on Rails Guides v2 - Ruby on Rails 4.2.5

    #### 三、创建一个新的Rails项目 - **步骤**:通过命令行使用`rails new project_name`来初始化一个新的Rails项目。 - **结构**:新项目将包含默认的目录结构,如`app`、`config`、`db`等,分别用于存放应用程序...

    Ruby On Rails中文教材(PDF)

    Ruby on Rails,简称Rails,是一款基于Ruby语言的开源Web应用框架,它遵循MVC(Model-View-Controller)架构模式,旨在简化Web应用程序的开发。Rails由David Heinemeier Hansson于2004年创建,它提倡“约定优于配置...

    Ruby On Rails教程

    - **创建新应用:** 使用Rails命令行工具可以快速创建一个新的Rails应用程序。例如,`rails new myapp`命令会为名为“myapp”的项目创建一个完整的目录结构和基础配置。 - **第一个应用:** 创建完应用后,可以通过...

    Ruby on Rails 教程 - 201406

    Ruby on Rails,简称ROR或Rails,是一款基于Ruby语言的开源Web应用框架,它遵循Model-View-Controller(MVC)架构模式,旨在提高开发效率和代码可读性。本教程“Ruby on Rails 教程 - 201406”可能是针对2014年6月时...

    Ruby on Rails入门权威经典

    接下来,书中会详细解释Rails的安装和配置过程,包括环境搭建、数据库配置以及Gemfile的使用,使读者能够快速创建并运行第一个Rails应用。同时,还会讲解Rails的核心组件,如路由、控制器、模型和视图,以及它们在...

    Ruby+on+Rails快速Web应用开发实战.pdf

    - **Ruby的社区与资源**:Ruby拥有一个活跃的社区,Ruby on Rails的快速发展与这个社区的贡献是分不开的。 ### Rails的安装与配置 - **Rails的安装环境**:文档提到了在Windows和Linux操作系统上安装Rails的步骤,...

    基于ruby on rails开发示例源码

    Ruby on Rails,简称Rails,是一种基于Ruby编程语言的开源Web应用程序框架,它遵循MVC(模型-视图-控制器)架构模式,旨在提高开发效率和代码的可读性。本示例源码提供了使用Ruby on Rails进行实际项目开发的具体...

    ruby on rails最佳敏捷开发

    Ruby on Rails,简称Rails,是一种基于Ruby语言的开源Web应用框架,它遵循敏捷开发原则,致力于简化Web开发过程。Rails的核心理念是“Convention over Configuration”(约定优于配置),这意味着开发者可以减少大量...

    ruby on rails 书全集(10余本经典著作PDF版)

    Ruby on Rails,简称Rails,是基于Ruby编程语言的一个开源Web应用程序框架,以其“约定优于配置”(Convention over Configuration)的设计哲学和“模型-视图-控制器”(MVC)架构模式,深受开发者喜爱。这套书全集...

    Ruby on Rails 指南 v5.0.1 中文版

    - **创建Rails项目**:介绍如何使用`rails new`命令来生成一个新的Rails项目,包括如何指定版本和其他选项。 - **Hello, Rails!**:通过一个简单的“Hello, World!”示例,让读者快速上手Rails的基本操作流程。 - **...

    ruby on rails社区网站开发源码

    Ruby on Rails,简称Rails,是由David Heinemeier Hansson创建的一个开源Web应用程序框架,它基于Ruby编程语言。这个框架以其MVC(Model-View-Controller)架构、约定优于配置(Convention over Configuration)的...

    Wrox - Beginning Ruby on Rails

    - **Rails入门**:讲解如何安装配置Ruby on Rails环境,以及创建第一个Rails应用的过程。 - **数据库交互**:教授如何在Rails应用中使用ActiveRecord来操作数据库。 - **控制器与视图**:介绍Rails中的控制器和视图...

    Agile Web Development With Ruby On Rails第一及第二版

    Ruby on Rails(简称Rails)是一个基于Ruby语言的开源Web应用程序框架,它遵循MVC(模型-视图-控制器)架构模式,旨在简化Web应用的开发过程,提高开发效率。Rails的核心理念是“约定优于配置”,这意味着在很多情况...

    ruby on rails 实践

    第一章“Ruby on Rails概述”,介绍了Ruby on Rails的基本概念和开发环境的搭建方法。通过这一章的学习,读者将对Rails框架有一个整体的认识,并了解如何搭建开发环境以及设计用户界面(UI)。 第二章“Rails中的...

    ruby on rails 学习资料

    Ruby on Rails,简称Rails,是一种基于Ruby编程语言的开源Web应用程序框架,它遵循MVC(模型-视图-控制器)架构模式,旨在提高开发效率和代码的可读性。Rails的核心理念是“DRY”(Don't Repeat Yourself),强调...

Global site tag (gtag.js) - Google Analytics