---
title: "ruby迁移任务基础"
author: "gift5168xf"
date: "2009-10-08T19:43:00Z"
tags: []
categories: ["编程语言"]
slug: "ruby"
draft: false
lastmod: "2009-10-14T01:39:20Z"
id: 487578
url: "https://sufery.iteye.com/blog/487578"
---

**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=&gt;false, ， :limit=&gt;100, ， :default=&gt;’priority’

Null 字段：值为 false 为 not null

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

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

**3** **字段改名**

rename\_column :orders( 表名 ) , ， :e\_mail( 被改字段名 ) ， :customer\_email( 修改名字字段 )

**4** **修改字段**

Change\_column :orders( 表名 ) ， :order\_type( 字段名 ) ， :string( 最终类型 ) ， :null=&gt;

**5** **表的管理**

1 表的创建

create\_table :order\_histories do |t|

t.integer :order\_id, :null =&gt; false

t.text :notes

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

2 表的重命名

rename\_table :order\_histories( 被修改的表名 ) , :order\_notes( 要修改的表名 )

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

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

**6** **定义索引**

Add\_index :orders( 表名 ) , :name( 索引所放位置 ) 移除： remove\_index ……..

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

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

**7** **主键**

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

create\_table :tickets, :primary\_key=&gt;number do |t|

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

End

没有主键的表：

create\_table :authors\_books :id=&gt;false do |t|

……

**8** **在迁移任务中加载数据**

模型 .create(: 属性 =&gt; 值，属性 =&gt; 值 ) 注： create 相当于模型 .new().save

**9** **从夹具中转载数据（略）**

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

Yml 数据的格式为：

……