LoginSignup
32
34

More than 5 years have passed since last update.

Railsマイグレーションのindex、foreign_keyの設定

Last updated at Posted at 2017-10-05

migrationファイルを書いていて、index,foreign_keyの設定の仕方でハマったので、調べたことを共有できればと思います

インデックス(index)

インデックスの追加(add_index)

基本的な書き方

# add_index :対象のテーブル名, インデックス対象のカラム名    
  add_index :company, :company_name

複合インデックスの場合

# add_index :対象のテーブル名, インデックス対象のカラム名  
  add_index :company, [:company_code, :compnay_name]

オプション

  1. 別名をつける場合
# add_index :対象のテーブル名, インデックス対象のカラム名, :name インデックスの別名    
  add_index :company, :company_name, name: :hogehuga_fk

インデックスの削除(remove_index)

# remove_index :対象のテーブル名, インデックス名  
  remove_index :company, name: :company_name_fk

外部キー(foreign_key)

外部キーの追加(add_foreign_key)

基本的な書き方

# add_foreign_key :対象のテーブル, :指定先のテーブル  
  add_foreign_key :companies, :accounts

複合外部キーの場合

対応していなさそうなので、SQL書いて頑張るしかなさそうです…

execute <<-SQL.gsub(/^\s+/, '')
  ALTER TABLE companies
  ADD company_type VARCHAR(255) NOT NULL DEFAULT 'Alliance',
  ADD CONSTRAINT companies_fk
  FOREIGN KEY (companies_division_id, company_type, company_id)
  REFERENCES company_divisions (id, company_type, company_id);
  SQL

オプション

  1. カラムの指定
# add_foreign_key :対象のテーブル, :指定先のテーブル, :column :対象のカラム名  
  add_foreign_key :companies, :accounts, column: :hoge_id
  1. 別名をつける場合
 # add_foreign_key :対象のテーブル, :指定先のテーブル, name: :foreign_keyの別名  
   add_foreign_key :companies, :accounts,  name: :huga_id

外部キーの削除(remove_foreign_key)

# remove_foreign_key :対象のテーブル, :指定先のテーブル  
  remove_foreign_key :companies, :accounts
32
34
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
32
34