Foreign Key Migrations in Rails 2.0
January 15th, 2008
Before Rails 2.0, adding a foreign key column to your migration was easy:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class CreateOfferGroupListings < ActiveRecord::Migration def self.up create_table :offer_group_listings do |t| t.integer :offer_id t.integer :offer_group_id t.integer :weight, :default => 0 t.timestamps end end def self.down drop_table :offer_group_listings end end |
With 2.0, it’s even EASIER!
1 2 3 4 5 6 7 8 9 10 11 12 | class CreateOfferGroupListings < ActiveRecord::Migration def self.up create_table :offer_group_listings do |t| t.references :offer, :offer_group t.integer :weight, :default => 0 t.timestamps end end def self.down drop_table :offer_group_listings end end |

January 18th, 2008 at 3:04 pm
Now does this actually create foreign key constraints at the DB level, or the same old software level key enforcement?
January 21st, 2008 at 12:05 pm
No it does not.
February 7th, 2008 at 4:20 pm
That’s weak. Why is rails so afraid of referential integrity?
July 22nd, 2008 at 2:12 pm
It’s very nice, but it doesn’t work:
add_column :jogos, :mapa, :references