Search code examples
sqlruby-on-railsassociationsone-to-manymodel-associations

What is the "Rails Way" to re-associate posts or other objects attached to a user when said user is deleted?


I am implementing a system where when a user deletes his/her account posts they have made will be re-associated to an anonymous account so they can still be displayed for other users of my site.

My site has a one_to_many association between users and posts.

There doesn't seem to be a matching option under dependent: _______ as can be seen here https://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many-label-Options

What I have done (and it is working) is added the following code to my destroy action inside of my user controller

    user = User.find_by(username: params[:username])
    admin_id = User.find_by(email: '[email protected]').id
    user.posts.each do |post|
      post.user_id = admin_id
      post.save
    end
    user.destroy

I figured that this is likely a common enough desire to have a more standard, "best practice" or "Railsy" way of accomplishing it, if there is what is it?


Solution

  • The dependent attribute doesn't have an option for what you are looking for. You can, however, use the before_destroy callback to modify the associated model.

    before_destroy :modify_association
    
    def modify_association
      associated_model.update(...)
    end
    

    You can read more about it here