Just do IT

思うは招く

Rails マイグレーション後、既存のテーブルカラム属性をインデックスにする方法

すでにマイグレーションをして、あとから特定のカラム属性にインデックスをつけたい場合

まずマイグレーションファイルを作成する。 例えば、Usersテーブルのemail属性にindexをつけたいとする。

rails g migration add_index_email_to_users

生成されたマイグレーションファイルに以下を追記。

class AddIndexEmailToUsers < ActiveRecord::Migration[6.0]
  def change
    add_index :users, :email, unique: true
  end
end

これでマイグレーションを実行。

rails db:migrate

するとスキーマファイルはこうなる。

ActiveRecord::Schema.define(version: 2020_02_12_060627) do

~
~

  create_table "users", force: :cascade do |t|
    t.string "name"
    t.string "email"
    t.string "password"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.index ["email"], name: "index_users_on_email", unique: true
  end

end

t.index ["email"], name: "index_users_on_email", unique: trueと、設定できていることがわかる。