This project is archived and is in readonly mode.

#4347 new
matthuhiggins

Add foreign key support to migrations and schema.rb dump

Reported by matthuhiggins | April 8th, 2010 @ 06:56 PM

This patch adds the following methods to migrations:

add_foreign_key(referencing_table, referenced_table, options = {})
remove_foreign_key(referencing_table, options)

change_table ... do |t|
  t.foreign_key(referenced_table, options)
  t.remove_foreign_key(options)
end

Options are :name, :column, :primary_key, :dependent.

In addition, ActiveRecord::SchemaDumper reads foreign keys from the SQL structure and puts them into schema.rb.


Some thoughts and concerns I came across while implementing this:

  • Extending t.references to automatically add a foreign key seems like a natural progression, but I didn't want to jam too much in at once.

  • The :primary_key value defaults to 'id'. This is a sensible default, but there is other code in the adapter that attempts to extract the primary key from the table. I do not know the history behind this, and was trying to clone the :primary_key API for associations.

  • Many active_record tests run with "use_transactional_fixtures = false", which results in leftover data during the foreign key tests. This makes adding foreign keys difficult, when the existing data has invalid references.

  • drop_table blows up if the table being dropped has foreign keys pointing to it. One option is to ignore foreign key checks during this (e.g. in MySql use "SET FOREIGN_KEY_CHECKS = 0; super; SET FOREIGN_KEY_CHECKS = 1;"

Comments and changes to this ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>

Attachments

Pages