0
0

Rails – 値が重複したレコードを削除してからDBに複合ユニーク制約を追加するマイグレーションの例

Last updated at Posted at 2023-08-24

問題

重複レコードが残ったままだとユニーク制約をDBに追加できない

Caused by:
Mysql2::Error: Duplicate entry '1-1' for key 'users.index_users_on_first_name_and_last_name'

  • first_name / last_name の組み合わせでDBにユニーク制約を持たせたい
  • first_name / last_name が同じ組み合わせのユーザは重複分のレコードを削除したい (1個だけ残したい)

という場合

コードの例

1個のマイグレーションでは重複レコードを削除する
up に ActiveRecord を直接書いてしまう

class RemoveDuplicateUsers < ActiveRecord::Migration[7.0]
  def up
    dupulicated_users = User.group(:first_name, :last_name).count.filter do |_k, v|
      v >= 2
    end

    dupulicated_users.each do |(first_name, last_name), _count|
      User.where(first_name:, last_name:).order(:id).drop(1).each(&:destroy)
    end
  end
end

次のマイグレーションでは普通に複合ユニーク制約を追加する

class AddUniquenessToUsers < ActiveRecord::Migration[7.0]
  def change
    add_index :users, %i[first_name last_name], unique: true
  end
end

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

https://twitter.com/YumaInaura
ra

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