迭代式开发rails应用(一)

记录学习rails的过程。应用来自《web敏捷开发之道——应用rails进行敏捷web开发》

1. 创建app

rails new test-depot --skip-bundle

cd test-depot

bundle install --local

修改GemFile,添加gem 'thin'

 

2.创建数据库表product

./script/rails generate scaffold product title:string description:string image_url:string 

rake db:migrate

3.启动服务
./script/rails s thin -p 4567

通过http://127.0.0.1:4567/products进行访问。可以通过页面中提供的create表单操作数据库。
 
4.增量修改数据库表结构
为数据库表product添加一列price。
./script/rails generate migration add_column
invoke  active_record
create    db/migrate/20121210082608_add_column.rb
 修改db/migrate/20121210082608_add_column.rb
class AddColumn < ActiveRecord::Migration
  def up
    add_column :products,:price,:decimal,:precision=>8,:scale=>2,:default=>0
  end

  def down
    remove_column :products,:price
  end
end
 运行rake db:migrate 
==  AddColumn: migrating ======================================================
-- add_column(:products, :price, :decimal, {:default=>0, :precision=>8, :scale=>2})
   -> 0.0051s
==  AddColumn: migrated (0.0052s) =============================================
由于添加了price列,但views中却没有实时添加上该字段,需要修改以下文件:
_form.html.erb edit.html.erb  index.html.erb new.html.erb   show.html.erb
照着其他字段的方法添加上price字段。 
最后在app/models/product.rb添加上price字段。
5.添加数据验证。
修改app/models/product.rb如下:
class Product < ActiveRecord::Base
  attr_accessible :description, :image_url, :title,:price
  validates_presence_of :title,:description,:image_url
#  validates_numericality_of :price
  validates_uniqueness_of :title
  validates_length_of :title,:minimum => 10
  validate :price_must_be_at_least_a_cent
  validates_format_of :image_url,:with=>%r{\.(gif|png|jpg)$}i,:message=>"must be a URL ForGIF,JPG or PNG image"
  def price_must_be_at_least_a_cent
    errors.add(:price,"should be at least 0.01") if price.nil?||price < 0.01
  end
end
 6.访问4567/products并填写数据如下:


7.添加css和一些样式
在app/assets目录下,有对应的目录如下:
images      
javascripts
stylesheets
只需要在这些文件目录下添加上对应的图片、js代码或css就可以了。

添加上我们的样式之后


 
 附件为test-depot,为整个应用程序

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值