Created
August 30, 2017 20:32
-
-
Save mkreyman/a305b47f653c40044f3757e37023b2af to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class AddUniquenessConstraintToUsersGuid < ActiveRecord::Migration | |
| def up | |
| # Delete all but the first user for users with duplicate :guid | |
| duplicate_guids = User.select(:guid).group(:guid).having('count(*) > 1').pluck(:guid) | |
| duplicate_guids.each do |duplicate_guid| | |
| next unless duplicate_guid.present? | |
| users_to_be_deleted = User.where(guid: duplicate_guid).order('id ASC')[1..-1] | |
| users_to_be_deleted.each(&:destroy) | |
| end | |
| change_table(:users, { bulk: true }) do |t| | |
| t.remove_index :guid | |
| t.index :guid, name: :index_users_on_unique_guid, unique: true | |
| end | |
| end | |
| def down | |
| change_table(:users, { bulk: true }) do |t| | |
| t.remove_index name: :index_users_on_unique_guid | |
| t.index :guid | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment