LoginSignup
0
0

More than 1 year has passed since last update.

railsの複合ユニークを追加するときに詰まったこと

Posted at

既に作成しているdbのカラムに複合ユニークを追加しようとした際に詰まったので記録。

原因

今回複合ユニークを設定しようとしたuser_idevent_idはt.referencesでカラムを作成していたため、既にindexがついていた。そのため、add_indexの構文で複合キーを設定しようとするともうそのindex名が存在するためエラーになる

吐かれたエラー

Mysql2::Error: Duplicate key name 'index_answers_on_event_id_and_user_id'

解決方法

一回、indexを削除して付与し直すという方法をとり、エラーを回避した。

class ChangeColumnSettingsFromAnswers < ActiveRecord::Migration[7.0]
  def change
    remove_index :answers, column: [:event_id, :user_id]
    add_index :answers, [:event_id, :user_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