rails3 数据 migration 之二 - 创建一个migration

来源:互联网 发布:多玩魔兽盒子mac版 编辑:程序博客网 时间:2024/06/07 22:57

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  endend

你可以追加任何你想加的字段。默认情况下,生成的migration会生成 t.timestamps 字段,

这是Active Record自动生成的updated_atcreated_at字段。


2.2 创建标准的migration

如果想创建另外目的的migration时(例如增加一个字段),你可以使用

migration产生的命令。

$ rails generate migration AddPartNumberToProducts
将会产生空的migration

class AddPartNumberToProducts < ActiveRecord::Migration  def change  endend
如果migration名字是 “AddXXXToYYY” 或者 “RemoveXXXFromYYY“并且后面跟着字段的参数和类型。

那么生成的migration里面 add_columnremove_column 语句将会被创建。

$ rails generate migration AddPartNumberToProducts part_number:string将会产生
class AddPartNumberToProducts < ActiveRecord::Migration  def change    add_column :products, :part_number, :string  endend

类似的

$ 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  endend

当然也可以增加多个字段

$ 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  endend
注意:如果你做一个表的列的删除之类的话,rails还是使用的旧的migration风格,就是有up 和down方法。 因为rails需要知道原来的列的类型。

原创粉丝点击