migration中でforeign_keyを書くメモ。
environment.rbとかに下記を書いておく。
module ActiveRecord::ConnectionAdapters::SchemaStatements
  def foreign_key(from_table, from_column, to_table)
    constraint_name = "fk_#{from_table}_#{to_table}" 
    execute "alter table #{from_table} add constraint #{constraint_name} foreign key (#{from_column}) references #{to_table}(id)" 
  end
end
migrationファイルにはこんな感じで書く。
class CreateCustomers < ActiveRecord::Migration
  def self.up
    create_table :customers do |t|
      t.references :user, :null => false
      (略)
    end
    foreign_key :customers, :user_id, :users
    add_index :customers, :user_id
  end
  def self.down
    drop_table :customers
  end
end
referencesって知らなかった。t.integer user_idって書くの何か気持ち悪かったんだけどこれですっきりしました。(何で気持ち悪いのかはわからない)
