Foreign Key Migrations in Rails 2.0

Before Rails 2.0, adding a foreign key column to your migration was easy:

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!

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

9 comments

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

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

  3. No it does not.

  4. No it does not.

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

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

  7. It’s very nice, but it doesn’t work:
    add_column :jogos, :mapa, :references

  8. It’s very nice, but it doesn’t work:
    add_column :jogos, :mapa, :references

  9. MySQL doesn't respect foreign key. So I think it's the reason why those constraints are not automaticly created. (MySQL sucks!)

Leave a comment