Agile Web Development

Build it. Launch it. Love it.

Foreign Key Migrations

Foreign Key Migrations is a plugin that automatically generates foreign-key constraints when creating tables. It uses SQL-92 syntax and as such should be compatible with most databases that support foreign-key constraints.

In the simplest case, the plugin assumes that if you have a column named customer_id that you want a foreign-key constraint generated that references the id column in the customers table:

  create_table :orders do |t|
    t.column :customer_id, :integer, :null => false
    ...
  end

If you have multiple columns referencing a table or for whatever reason, your column name isn’t the same as the referenced table name, you can use the :references option:

  create_table :orders do |t|
    t.column :ordered_by_id, :integer, :null => false, :references => :customers
    ...
  end

If you have a column with a name ending in _id for which you do not wish a foreign-key to be generated, you can use :references => nil:

  create_table :orders do |t|
    t.column :external_id, :integer, :null => false, :references => nil
    ...
  end

You also have the option of specifying what to do on delete/update using :on_delete/:on_update, respectively to one of: :cascade; :restrict; and :set_null:

  create_table :orders do |t|
    t.column :customer_id, :integer, :on_delete => :set_null, :on_update => :cascade
    ...
  end

The plugin fully supports and understands the following active-record configuration properties:

  • config.active_record.pluralize_table_names
  • config.active_record.table_name_prefix
  • config.active_record.table_name_suffix

Dependencies

  • RedHill on Rails Core (redhillonrails_core).

See Also

  • Foreign Key Associations (foreign_key_associations).

Vitals

Home http://www.redhillconsulting.com.au/rails_plugins.html
Repository svn://rubyforge.org/var/svn/redhillonrails/trunk/vendor/plugins/foreign_key_migrations
License Rails' (MIT)
Rating (21 votes)
Owner Red Hill Consulting
Created 26 May 2006

Comments

  • Avatar
    Eric Anderson
    9 August 2006

    I tried this plugin because I figure the more checks for valid data the better. The problem is when I tried to execute my unit testing it failed to load the fixtures since the records were inserted in an improper order. Any ideas on how to get around this.

  • Avatar
    24 August 2006

    Hmm...it shouldn't be adding the foreign keys to your test database. any chance you could email me some sample code?

  • Avatar
    Eric Pugh
    1 September 2006

    I also have FK's in the test environment. It was quite the project to figure out the issue, and I learned a lot! I tweaked init.rb to have a if statement: if ENV["RAILS_ENV"] != "test"

    and also useing migrations for building the test db instead of using the rake clonestructureto_test call.

Add a comment