2.1 新建一个模型(model)
通过rails里面的脚手架可以创建一个模型。生成模型的同时,
也同时生成了建表的migration。如果你生成model时指定了
字段,migration里面也会生成对应的字段。
例如:
$ rails generate model Product name:string description:text
生成的migration如下
class CreateProducts < ActiveRecord::Migration
def change
create_table :products do |t|
t.string :name
t.text :description
t.timestamps
end
end
end
你可以追加任何你想加的字段。默认情况下,生成的migration会生成 t.timestamps 字段,
这是Active Record自动生成的updated_at 和created_at字段。
2.2 创建标准的migration
如果想创建另外目的的migration时(例如增加一个字段),你可以使用
migration产生的命令。
$ rails generate migration AddPartNumberToProducts
将会产生空的migration
class AddPartNumberToProducts < ActiveRecord::Migration
def change
end
end
如果migration名字是 “AddXXXToYYY” 或者 “RemoveXXXFromYYY“并且后面跟着字段的参数和类型。
那么生成的migration里面 add_column和 remove_column 语句将会被创建。
$ rails generate migration AddPartNumberToProducts part_number:string
将会产生
class AddPartNumberToProducts < ActiveRecord::Migration
def change
add_column :products, :part_number, :string
end
end
类似的
$ rails generate migration RemovePartNumberFromProducts part_number:string
将会产生
class RemovePartNumberFromProducts < ActiveRecord::Migration
def up
remove_column :products, :part_number
end
def down
add_column :products, :part_number, :string
end
end
当然也可以增加多个字段
$ rails generate migration AddDetailsToProducts part_number:string price:decimal
将会产生
class AddDetailsToProducts < ActiveRecord::Migration
def change
add_column :products, :part_number, :string
add_column :products, :price, :decimal
end
end
注意:如果你做一个表的列的删除之类的话,rails还是使用的旧的migration风格,就是有up 和down方法。 因为rails需要知道原来的列的类型。