Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...