ITeye博客

ruby迁移任务基础

gift5168xf · 2009-10-08 19:43 · ROR · 编程语言 · Markdown

1 运行迁移任务

Rake db:migrate

数据库中 schema_info 表记录 version 的当前版本信息如: 20081230025725

2 字段类型

通过迁移任务可以把任务中的程序数据类型转换成数据库相对应的类型

类型包括: binary 、 boolean 、 date 、 datetime 、 decimal 、 float 、 integer 、 string 、 text 、 time 、 timeestamp

增加字段: add_column:orders( 表名 ) , , :e_mail( 字段名 ) ,

:string( 字段类型 ) , :null=>false, , :limit=>100, , :default=>’priority’

Null 字段:值为 false 为 not null

Limit 字段:设置字段大小限制

Default 字段:设置字段的默认值

3 字段改名

rename_column :orders( 表名 ) , , :e_mail( 被改字段名 ) , :customer_email( 修改名字字段 )

4 修改字段

Change_column :orders( 表名 ) , :order_type( 字段名 ) , :string( 最终类型 ) , :null=>

5 表的管理

1 表的创建

create_table :order_histories do |t|

t.integer :order_id, :null => false

t.text :notes

t.timestamps 注:两个颜色部分的内容必不可少

2 表的重命名

rename_table :order_histories( 被修改的表名 ) , :order_notes( 要修改的表名 )

为保证迁移任务能够运行,保证如果在建表时还没有表对应的类,应

在迁移任务中首先定义一个类来站位,以保证迁移任务不会出错。

6 定义索引

Add_index :orders( 表名 ) , :name( 索引所放位置 ) 移除: remove_index ……..

若加入参数 :unique=>true 表示被索引字段值必须唯一

注:移除索引时也必须加入字段名

7 主键

改变主键名称:在建立表的时候改变

create_table :tickets, :primary_key=>number do |t|

其他属性不变,不需加入新改变的主键属性

End

没有主键的表:

create_table :authors_books :id=>false do |t|

……

8 在迁移任务中加载数据

模型 .create(: 属性 => 值,属性 => 值 ) 注: create 相当于模型 .new().save

9 从夹具中转载数据(略)

首先创建夹具文件:在 migration 下建立文件夹,在文件夹中建立数据文件 .yml

Yml 数据的格式为:

……

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。