Skip to main content

How do I transfer user data on delete

Rails • Asked by Stephen Sizer
I have a rails app with company users using devise. I want to be able to delete users and select an employee to transfer the foreign keys to.

Hope that makes sense? Thanks in advance

You may have to divide and conquer the steps first. 

1. Identify the users you want to delete
2. Identify the employee
3. Transfer id
4. then delete user

depending on the table, you could use SQL to a large update provided you're able to find the users


UPDATE employees
LEFT OUTER JOIN user
    ON "{your condition}"
SET  employee.foreign_key = user.foreign_key
WHERE {condition}

I know it's not an exact answer but might point you in the right diraction



To give more context:

I have a users table

Then i have the following tables that also the user_id column

Courses
Notes
Comments
Questions
Answers

What I want to be able to do is. If a member of the team leaves I want to be able to assign all courses, notes, comments, questions and answers over to another user that already exists.

Thanks,
Steve


Interesting. I think you could use callback for delete

class User < ActiveRecord::Base
  before_destroy :assign_courses

  private

  def assign_courses
    new_user = User.new_user_responible #some way of finding the next user responsible
    courses.update_all(user: new_user)
  end
end

Then you would just create a method for each table you want to transfer. 

assign_questions

You will also need to implement some scope on your User model to find the employee who is going to be assigned all the notes. 

I was thinking of having a page before delete that would populate a list of users to transfer the data to and then on that action it would delete the user :)

That's a good idea. Having a step-by-step process for deletion. Then you can just capture the new user who going to get everything transferred to. Best of luck. Hope I was able to help a little

Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 27,623+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.