This project is archived and is in readonly mode.
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
-
matthuhiggins April 8th, 2010 @ 09:52 PM
foreign_keys-2.diff tests that foreign keys are dumped to schema.rb after the tables
-
wtn November 23rd, 2010 @ 11:58 AM
-1
I'm fine with using existing gems and leaving this out of the official AR.
-
Daniel November 23rd, 2010 @ 08:16 PM
+1 Migrations have always felt incomplete to me because they lack support for adding foreign key constraints. I greatly appreciate the Foreigner gem, but I would really like to see foreign keys supported in the framework.
-
Michał Łomnicki January 12th, 2011 @ 11:39 AM
+1 for foreign keys
It is absolute must-have for ActiveRecord. Foreign keys are the only way to keep relations consistent as validations are prone to race conditions and one can't really rely on them.
-
Ryan January 14th, 2011 @ 02:24 AM
+1 This is absolutely necessary. Foreign keys should definitely be supported out of the box for migrations.
-
Franco Catena February 15th, 2011 @ 10:20 PM
+1 for me too. I agree, is the one thing that was always missed in migrations.
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>