Skip to content

cjohansen.no

mysql_foreign_keys

A Rails plugin that adds two methods to migrations that allows you to add and remove MySQL foreign keys.

Rails migrations offers to link tables together by means of the t.references method. However, this only creates an integer column, but no physical foreign key. mysql_foreign_key fixes that.

Installation

script/plugin install http://svn.cjohansen.no/rails/plugins/mysql_foreign_keys/trunk

Usage

mysql_foreign_keys is used in migrations:

class CreatePeople < ActiveRecord::Migration
  def self.up
    create_table :people do |t|
      t.string :name, :null => false
      t.references :address
    end

    add_foreign_key :people, :addresses
  end

  def self.down
    drop_table :people
  end
end

If the foreign key column is not named like address_id you can override it by doing add_foreign_key :people, :addresses, :location_id.

More ideas

Ideally the plugin should also hook into ActiveRecord::ConnectionAdapters::Table#references, automatically adding foreign keys for columns added with the references method.

2006 - 2012 Christian Johansen Creative Commons License