migrationでforeign keyを定義する

UsingMigrations in Ruby on Rails

class CreateLineItems < ActiveRecord::Migration
  def self.up
    create_table(:line_items) do |t|
      t.column(:product_id, :integer, :null => false)
      t.column(:quantity, :integer, :null => false, :default => 0)
    end
    # This line is required if you're running a version of MySQL prior to 4.1.2
    #add_index(:line_items, [:product_id], :name => 'fk_line_items_product')
    execute('ALTER TABLE line_items ADD CONSTRAINT fk_line_items_product FOREIGN KEY ( product_id ) REFERENCES products( id ) ')
  end
  def self.down
    drop_table(:line_items)
  end
end