一直知道rails里面用migrate来进行数据库的版本控制,还是比较浅显易懂,做做笔记。
RoR的官方Wiki上有两篇文章:
http://wiki.rubyonrails.com/rails/pages/UnderstandingMigrations
http://wiki.rubyonrails.com/rails/pages/UsingMigrations
如何使用:
1. Create a migration
ruby 代码
- ruby script/generate migration description_of_migration
命名提示:
a.Migration的命名规则和model,controller一样
b.给一个mingration取一个和已经有的model类一样的名字会导致rake db:migrate诡异地失败(??未测试)
2. Edit the code to tell it what to do.
Edit the newly created file (in db/migrate). Define the up and a down methods.
3. Run the migration with Rake
ruby 代码
Tables
create_table
一个ID字段(主健)会被自动创建,对于has_and_belongs_to_many表来说,可以用:id=>false来取消
ruby 代码
- class AddTags < ActiveRecord::Migration
- def self.up
- create_table :images_tags, :id => false do |table|
- table.column :image_id, :integer
- table.column :tag_id, :integer
- end
- create_table :tags do |table|
- table.column :name, :string
- end
- end
-
- def self.down
- drop_table :tags
- drop_table :images_tags
- end
- end
合法的字段类型包括:integer, float, datetime, date, timestamp, time, text, string, binary, and boolean. 合法的字段选项包括:limit, null (比如说 :null => false 表示 NOT NULL), 以及 default (来设定默认值).
create_table可以有很多参数(见API参考)。有一个是options,可以将用原始的sql语句来添加到表后面作限制,比如说字符编码,表的类型等,比如:
ruby 代码
- create_table(:families, :options => 'DEFAULT CHARSET=UTF8') do |t|
Columns
Migrations work with columns in create_table and also with add_column.
Options when running rake db:migrate
Migrate to a specific version
ruby 代码
- rake db:migrate VERSION=17
Migrate a specific database
ruby 代码
- rake environment RAILS_ENV=production db:migrate