LoginSignup
0
0

More than 3 years have passed since last update.

foreign keyを付与する際に作ったindexの更新をする方法

Posted at

タイトルのまんまです
結構ハマったので備忘録もかねて書いておきます
例えば、既存のindexを更新する場合は、以下のように書けばうまく行くと思います

class AddIndexSample < ActiveRecord::Migration[5.2]
  def change
    remove_index :users, :type_id
    add_index :users, :type_id, unique: true
  end
end

これはすでにusersテーブルのtype_idというカラムに対して、indexが貼られていて、そのindexを更新するための方法です

ですが、foreign_keyが貼られている場合はindexを削除しようとするとエラーが出てしまいます
なのでforeign_keyを削除してからindexを削除して更新するとうまくいきます

class AddIndexSample < ActiveRecord::Migration[5.2]
  def change
    remove_foreign_key :users, :types # 第二引数はテーブル名
    remove_index :users, :type_id
    add_foreign_key :users, :types
    add_index :users, :type_id, unique: true
  end
end
0
0
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
0
0