Ask A Question

Notifications

You’re not receiving notifications from this thread.

How do I transfer user data on delete

Stephen Sizer asked in Rails
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
Reply
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


Reply
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

Reply
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. 
Reply
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 :)
Reply
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
Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 85,376+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.