Rails 把資料庫分成三種~ 開發用資料庫(_development)、測試用資料庫(_test)、成品資料庫(_production)
先建立三個資料庫~分別是(只要在前面加上專案名稱及可)
demo_development
demo_test
demo_production
接著到 guest\config\database.yml 設定連接的資訊(位置、資料庫名稱、帳號密碼)
- development:
- adapter: mysql
- encoding: utf8
- database: demo_development
- username: root
- password: xxxxxx
- host: localhost
- test:
- adapter: mysql
- encoding: utf8
- database: demo_test
- username: root
- password: xxxxxx
- host: localhost
- production:
- adapter: mysql
- encoding: utf8
- database: demo_production
- username: root
- password: xxxxxx
- host: localhost
接著到 console 底下輸入
rake db:migrate
進行遷移
如看到類似
(in x:/x/demo)
之類的資訊就是成功
不過如果出現
rake aborted!
Mysql::Error: #HY000The ‘InnoDB’ feature is disabled; you need MySQL built with ‘InnoDB’ to have it working
的話,先設定 Mysql 的 my.ini 裡面找到
#skip-innodb
把他前面的 # 拿掉,讓他enable 即可 (我的反而是讓他disable 以後才啟動成功…怪…)
到這邊我開始想我要寫什麼當練習… 好= = 簡易流言版ˊˋ|||…
接著建立一個database table 、一個model讓我們的app去控制那些table、一些views、一個controller .
接著留言板就讓他有很基本的… 姓名(name)、Email(email)、留言(content)…恩,先這樣就好~
ruby script/generate scaffold post name:string email:string content:string
得到
- C:\ror\demo>ruby script/generate scaffold post name:string email:string content:string
- exists app/models/
- exists app/controllers/
- exists app/helpers/
- create app/views/posts
- exists app/views/layouts/
- exists test/functional/
- exists test/unit/
- exists public/stylesheets/
- create app/views/posts/index.html.erb
- create app/views/posts/show.html.erb
- create app/views/posts/new.html.erb
- create app/views/posts/edit.html.erb
- create app/views/layouts/posts.html.erb
- create public/stylesheets/scaffold.css
- create app/controllers/posts_controller.rb
- create test/functional/posts_controller_test.rb
- create app/helpers/posts_helper.rb
- route map.resources :posts
- dependency model
- exists app/models/
- exists test/unit/
- exists test/fixtures/
- create app/models/post.rb
- create test/unit/post_test.rb
- create test/fixtures/posts.yml
- create db/migrate
- create db/migrate/20080807082537_create_posts.rb
這一串呢… 是用scaffold 建立一個叫post的model , 還有一個 posts 的 controller , 順便也為posts controller 建立個相關的 views,還有一份很重要的migration ~
那一份migration(20080807082537_create_posts.rb) 內容如下
- class CreatePosts < ActiveRecord::Migration
- def self.up
- create_table :posts do |t|
- t.string :name
- t.string :email
- t.string :content
- t.timestamps
- end
- end
- def self.down
- drop_table :posts
- end
- end
裡面包含 self.up 和 self.down 兩個方法
self.up 是在資料庫版本升級時會用到的,反之降級用self.down
在 self.up 中可以看到在做 db:migrate 的背後,這幾行幫我們建立了name , email , content 三個資料欄位
self.down 則是降級時刪除這個table …
接著我們只要再下一次
rake db:migrate
就遷移(升級)成功~
Scaffold 中譯 "鷹架",如其名 … 他就把基本的架構快速搞出來,簡單用…
現在打開 webrick 就能看到結果了….
0個對 “[Rails] Rails 學習筆記(2)” 的回應