记录学习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并填写数据如下:
![](http://dl.iteye.com/upload/attachment/0077/6858/9579a811-2020-3de0-b063-d43df5d915fc.png)
7.添加css和一些样式
在app/assets目录下,有对应的目录如下:
images
javascripts
stylesheets
只需要在这些文件目录下添加上对应的图片、js代码或css就可以了。
添加上我们的样式之后
![](http://dl.iteye.com/upload/attachment/0077/6877/f505e2cf-cfa2-31b2-8762-432e1237106c.png)
附件为test-depot,为整个应用程序