---
title: "让ROR的Migration自动加外键约束"
author: "ron"
date: "2007-10-18T01:51:58Z"
tags: []
slug: "ror-migration"
draft: false
lastmod: "2007-10-18T01:51:58Z"
id: 133010
url: "https://ron.iteye.com/blog/133010"
---

Activerecord 挺方便的，但是就是不能自动加外键约束。突然记起来在《Agile Web Development with Rails》书中提到有一个plug-in可以解决这个问题。果然得到以下成果：

**出处：**  
http://www.redhillonrails.org/  
这是个很好的ROR插件网站，其中就有解决上面提到的问题的插件。

**安装插件：**  
在项目目录下运行：  
`ruby script/plugin install http://www.redhillonrails.org/svn/trunk/vendor/plugins/redhillonrails_core ruby script/plugin install http://www.redhillonrails.org/svn/trunk/vendor/plugins/foreign_key_migrations 示例：`

ruby 代码

1. create\_table :orders do |t|
2. t.column :ordered\_by\_id, :integer, :null =&gt; false, :references =&gt; :customers
3. ...
4. end

在运行ruby db:migrate后，检查schema.rb文件，就会发现add\_foreign\_key之类的语句，再检查数据库，果然有外键了。

**说明：**  
1、关于数据库的支持，官方文档中提到：Using SQL-92 syntax and as such should be compatible with most databases that support foreign-key constraints.  
2、用NETBEANS工具中用窗口创建plug-in不行，估计是NETBEANS 6 B1的一个bug吧。一定要用命令行安装插件，我就是在这个上面上当了，搞到现在才可以睡觉。  
3、详细的使用说明见上面提到的官方网站。