更新到最新版本:
rake db:migrate
重设数据库:
rake db:migrate VERSION=0
字段操作
1、字段类型
:binary, :boolean, :date, :datetime, :float, :integer, :string, :text, :time, :timestamp
2、add_column 添加字段
参数
:null => true or false 是否可为null
:limit => size 字段大小,通常是string字段的长度
:default => value 缺省的值
-
add_column
:orders
,
:placed_at
,
:datetime
,
:default
=>
Time
.now
3、rename_column 字段名修改
-
class
RenameEmailColumn < ActiveRecord::Migration
-
def
self
.up
-
rename_column
:orders
,
:e_mail
,
:customer_email
-
end
-
def
self
.down
-
rename_column
:orders
,
:customer_email
,
:e_mail
-
end
-
end
4、change_column 字段类型属性修改
-
def
self
.up
-
change_column
:orders
,
:order_type
,
:string
,
:null
=>
false
-
end
-
def
self
.down
-
change_column
:orders
,
:order_type
,
:integer
-
end
表操作
-
class
CreateOrderHistories < ActiveRecord::Migration
-
def
self
.up
-
create_table
:order_histories
do
|t
|
-
t.column
:order_id
,
:integer
,
:null
=>
false
-
t.column
:created_at
,
:timestamp
-
t.column
:notes
,
:text
-
end
-
end
-
def
self
.down
-
drop_table
:order_histories
-
end
-
end
重命名rename_table
索引
-
class
AddCustomerNameIndexToOrders < ActiveRecord::Migration
-
def
self
.up
-
add_index
:orders
,
:name
-
end
-
def
self
.down
-
remove_index
:orders
,
:name
-
end
-
end
PK
-
create_table
:tickets
,
:primary_key
=>
:ticket_number
do
|t
|
-
t.column
:created_at
,
:timestamp
-
t.column
:description
,
:text
-
end
raise ActiveRecord::IrreversibleMigration 不可逆错误
-
class
ChangeOrderTypeToString < ActiveRecord::Migration
-
def
self
.up
-
change_column
:orders
,
:order_type
,
:string
,
:null
=>
false
-
end
-
def
self
.down
-
raise
ActiveRecord::IrreversibleMigration
-
end
-
end