---
title: "Rails Migration"
author: "cowoo"
date: "2007-04-18T00:23:38Z"
tags: []
slug: "rails-migration"
draft: false
lastmod: "2007-04-18T00:23:38Z"
id: 72011
url: "https://cowoo.iteye.com/blog/72011"
---

一直知道rails里面用migrate来进行数据库的版本控制，还是比较浅显易懂，做做笔记。

RoR的官方Wiki上有两篇文章：  
http://wiki.rubyonrails.com/rails/pages/UnderstandingMigrations  
http://wiki.rubyonrails.com/rails/pages/UsingMigrations

如何使用：  
1\. Create a migration

ruby 代码

1. ruby script/generate migration description\_of\_migration

命名提示：  
a.Migration的命名规则和model，controller一样  
b.给一个mingration取一个和已经有的model类一样的名字会导致rake db:migrate诡异地失败(??未测试）  
   
2\. Edit the code to tell it what to do.

Edit the newly created file (in db/migrate). Define the up and a down methods.

3\. Run the migration with Rake

ruby 代码

 

1. rake db:migrate

**Tables**  
create\_table  
一个ID字段(主健）会被自动创建，对于has\_and\_belongs\_to\_many表来说，可以用:id=&gt;false来取消

 

ruby 代码

 

01. class AddTags &lt; ActiveRecord::Migration
02. def self.up
03. create\_table :images\_tags, :id =&gt; false do |table|
04. table.column :image\_id, :integer
05. table.column :tag\_id, :integer
06. end
07. create\_table :tags do |table|
08. table.column :name, :string
09. end
10. end
11. def self.down
12. drop\_table :tags
13. drop\_table :images\_tags
14. end
15. end

   
合法的字段类型包括：integer, float, datetime, date, timestamp, time, text, string, binary, and boolean. 合法的字段选项包括：limit, null (比如说 :null =&gt; false 表示 NOT NULL), 以及 default (来设定默认值).

create\_table可以有很多参数（见API参考）。有一个是options，可以将用原始的sql语句来添加到表后面作限制，比如说字符编码，表的类型等，比如：

ruby 代码

 

1. create\_table(:families, :options =&gt; 'DEFAULT CHARSET=UTF8') do |t|

 **Columns**  
 Migrations work with columns in create\_table and also with add\_column.

 **Options when running rake db:migrate**  
 Migrate to a specific version

ruby 代码

 

1. rake db:migrate VERSION=17

   
 Migrate a specific database

ruby 代码

 

1. rake environment RAILS\_ENV=production db:migrate