ITeye博客

让ROR的Migration自动加外键约束

ron · 2007-10-18 01:51 · Markdown

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 => false, :references => :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、详细的使用说明见上面提到的官方网站。

评论(1)

  1. #1 楼 · dazuiba · 2007-11-12 21:28

    加fk constraint,会让你的数据维护很麻烦。 比如你一个tree model,一句delete是不能删除的。 除非将mysql置为 NOCHECK CONSTRAINT。 这在fixtures方式维护测试数据时,是相当恼火的。

    我一般这样折衷: 所有非空fk,加上:null=>false 而外建引用非空是很常见的(几乎所有:belongs_to都要求外建非空),所以我修改了sex_migrate的foreign_key方法,让他默认加上非空约束

    def foreign_key(*args)
          options = args.last.is_a?(Hash) ? args.pop : {}
          options[:null]=false unless options.has_key?(:null)
          args.each do |col| 
            column(id = "#{col}_id", :integer, options)
            if options[:ref]
              reference = options[:ref] == true ? col.to_s.tableize : options[:ref].to_s 
              (@fk_references ||= []) << [id, reference]
            end
          end 
        end
    
    

    使用时,默认就是非空,除非指定

    
        create_table "topics", :force => true do |t|
          foreign_key "forum"
          foreign_key "root_post",:null => true 
        end
    

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