Rails 除了生成空項(xiàng)目什么都沒做,但是可以看到它正在為您工作。清單 2 創(chuàng)建的目錄中包含:
應(yīng)用程序目錄,包括模型、視圖和控制器的子目錄
單元測(cè)試、功能測(cè)試和集成測(cè)試的測(cè)試目錄
為測(cè)試而明確創(chuàng)建的環(huán)境
測(cè)試用例結(jié)果的日志
因?yàn)?Rails 是一個(gè)集成環(huán)境,所以它可以假設(shè)組織測(cè)試框架的佳方式。Rails 也能生成默認(rèn)測(cè)試用例,后面將會(huì)看到。
現(xiàn)在要通過遷移創(chuàng)建數(shù)據(jù)庫表,然后用數(shù)據(jù)庫表創(chuàng)建新數(shù)據(jù)庫。請(qǐng)鍵入 cd trails 進(jìn)入 trails 目錄。然后生成一個(gè)模型和遷移(migration),如清單 3 所示:
清單 3. 生成一個(gè)模型和遷移
> script/generate model Trail
exists app/models/
exists test/unit/
exists test/fixtures/
create app/models/trail.rb
create test/unit/trail_test.rb
create test/fixtures/trails.yml
create db/migrate
create db/migrate/001_create_trails.rb
注意,如果使用 Windows,必須在命令前加上 Ruby,這樣命令變成了 ruby script/generate model Trail。
如清單 3 所示,Rails 環(huán)境不僅創(chuàng)建了模型,還創(chuàng)建了遷移、測(cè)試用例和測(cè)試 fixture。稍后將看到 fixture 和測(cè)試的更多內(nèi)容。遷移讓 Rails 開發(fā)人員可以在整個(gè)開發(fā)過程中處理數(shù)據(jù)庫表中不可避免的更改(請(qǐng)參閱 跨越邊界:研究活動(dòng)記錄)。請(qǐng)編輯您的遷移(在 001_create_trails.rb 中),以添加需要的列,如清單 4 所示:
清單 4. 添加列
class CreateTrails < ActiveRecord::Migration
def self.up
create_table :trails do |t|
t.column :name, :string
t.column :description, :text
t.column :difficulty, :string
end
end
def self.down
drop_table :trails
end
end
您需要?jiǎng)?chuàng)建和配置兩個(gè)數(shù)據(jù)庫:trails_test 和 trails_development。如果想把這個(gè)代碼投入生產(chǎn),那么還需要?jiǎng)?chuàng)建第三個(gè)數(shù)據(jù)庫 trails_production,但是現(xiàn)在可以跳過這一步。請(qǐng)用數(shù)據(jù)庫管理器創(chuàng)建數(shù)據(jù)庫。我使用的是 MySQL:
清單 5. 創(chuàng)建開發(fā)和測(cè)試數(shù)據(jù)庫
mysql> create database trails_development;
Query OK, 1 row affected (0.00 sec)
mysql> create database trails_test;
Query OK, 1 row affected (0.00 sec)
然后編輯 config/database.yml 中的配置,以反映數(shù)據(jù)庫的優(yōu)先選擇。我的配置看起來像這樣:
清單 6. 將數(shù)據(jù)庫適配器添加到配置中
development:
adapter: mysql
database: trails_development
username: root
password:
host: localhost
test:
adapter: mysql
database: trails_test
username: root
password:
host: localhost
現(xiàn)在可以運(yùn)行遷移,然后把應(yīng)用程序剩下的部分搭建(scaffold)在一起:
清單 7. 遷移和搭建
> rake migrate
...results deleted...
> script/generate scaffold Trail Trails
...results deleted...
create app/views/trails
...results deleted...
create app/views/trails/_form.rhtml
create app/views/trails/list.rhtml
create app/views/trails/show.rhtml
create app/views/trails/new.rhtml
create app/views/trails/edit.rhtml
create app/controllers/trails_controller.rb
create test/functional/trails_controller_test.rb
...results deleted...