Merging User Accounts - department-of-veterans-affairs/caseflow GitHub Wiki

Occasionally we must merge User accounts. Examples include if a user has a name change and their CSS ID changes, the next time they log in to Caseflow it will create a new User record with no association to their old User record. (Ideally they would tell us ahead of time and we could just change the CSS ID on the existing User record before they log in with the new CSS ID, but ideals have a way of falling short sometimes.)

Steps

Ask the user to avoid logging into Caseflow while you're performing these steps

Identify the new_user and old_user records

In this example we are going to merge all the new_user associated records to the old_user, delete the new_user, and rename the old_user CSS ID.

Run the UserReporter on the record to delete

> ur = UserReporter.new(new_user)
> ur.report
=> ["13508 has 81 Annotation.user_id", "13508 has 7 ClaimsFolderSearch.user_id", "13508 has 1 OrganizationsUser.user_id", "13508 has 20 AppealView.user", "13508 has 1913 DocumentView.user"]

Update the old record associations

You can refer to the models listed in the UserReporter output. Example clean up looks like:

Annotation.where(user: new_user).update_all(user_id: old_user.id)

Some models have unique indexes and trying to insert new records will collide because the old user already has existing records with the corresponding values. Examples are DocumentView and AppealView. To work around this, since we want to skip the duplicates, we can just rescue the error and interate:

begin
  AppealView.where(user: new_user).each do |dv|
    dv.update(user_id: old_user.id)
  rescue ActiveRecord::RecordNotUnique
    dv.delete # because we already have the view recorded under old_user
  end
end

Delete the new_user

> new_user.destroy

Rename the old_user

Use the new CSS ID

> old_user.update!(css_id: new_user.css_id)