星期日, 5月 20, 2012

[RoR] 如何連接資料庫

Rails內建的資料庫是採用SQLite,資料庫的設定檔在此目錄下:config/database.yml


# SQLite version 3.x
#   gem install sqlite3
#
#   Ensure the SQLite 3 gem is defined in your Gemfile
#   gem 'sqlite3'
development:
  adapter: sqlite3
  database: db/development.sqlite3
  pool: 5
  timeout: 5000

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  adapter: sqlite3
  database: db/test.sqlite3
  pool: 5
  timeout: 5000

production:
  adapter: sqlite3
  database: db/production.sqlite3
  pool: 5
  timeout: 5000

建立一個Model
$>rails g model users account:string password:string

      invoke  active_record
      create    db/migrate/20120520124738_create_users.rb
      create    app/models/users.rb
      invoke    test_unit
      create      test/unit/users_test.rb
      create      test/fixtures/users.yml

使用migrate建立資料表

$> bundle exec rake db:migrate

==  CreateUsers: migrating ====================================================
-- create_table(:users)
   -> 0.0014s
==  CreateUsers: migrated (0.0015s) ===========================================

新增一個descript欄位到users表格

rails g migration add_descript_to_users
      invoke  active_record
      create    db/migrate/20120520125033_add_descript_to_users.rb


執行migrate將剛新增的欄位加入

$>bundle exec rake db:migrate
==  AddDescriptToUsers: migrating =============================================
==  AddDescriptToUsers: migrated (0.0000s) ====================================


TIP:Rails會知道哪些已經執行過migration,所以只會執行一次


Rake指令集
rake db:create # to create database
rake db:migrate # to create tables based on your migration







沒有留言:

張貼留言

留個話吧:)

其他你感興趣的文章

Related Posts with Thumbnails