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

3 Responses to “Foreign Key Migrations in Rails 2.0”

  1. Duro Says:

    Now does this actually create foreign key constraints at the DB level, or the same old software level key enforcement?

  2. Jonathan Says:

    No it does not.

  3. Geoff Says:

    That’s weak. Why is rails so afraid of referential integrity?

Leave a Reply