Skip to content

Instantly share code, notes, and snippets.

@mkreyman
Created August 30, 2017 20:32
Show Gist options
  • Select an option

  • Save mkreyman/a305b47f653c40044f3757e37023b2af to your computer and use it in GitHub Desktop.

Select an option

Save mkreyman/a305b47f653c40044f3757e37023b2af to your computer and use it in GitHub Desktop.
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