All threads / How do I transfer user data on delete
Ask A Question


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
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
    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


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.


Interesting. I think you could use callback for delete

class User < ActiveRecord::Base
  before_destroy :assign_courses


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

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


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
Join the discussion

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

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

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

    logo Created with Sketch.

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more. Icons by Icons8

    © 2023 GoRails, LLC. All rights reserved.