简体   繁体   中英

How do I keep a user even after they've been deleted?

Let's say I have a user created, who leaves some comments on my site, and then I delete them using @user.destroy.

Now when I display the comments, it throws up errors because @user is nil for the comments they've written.

What would be a good approach to fixing this, considering that:

  • I would still like to be able to delete users (at least superficially)
  • I would like the user to be able to be re-signed up using the same credentials.

I usually use a field called deleted_at then define a model method archive which populates the deleted_at with the current time and saves. Default scope for the model is then where('deleted_at IS NULL') (or where{deleted_at == nil} if you love squeel like I do).

I use this for much more than my user models. I even have the functionality abstracted away so in each model I want archivable I just do archived_by :deleted_at in the model. There are likely places in your app where you have to check and see if the requested record is archived/deleted, but for the most part this is a simple and elegant solution. Bringing a record back from being deleted/archived is as simple as record.deleted_at = nil (or record.archive(false) / record.unarchive if you prefer).

For this to be performant on a large table I recommend indexing the deleted_at column.

Another idea that is simpler is to put a boolean field called trashable and use a concern to define scopes (as @dhh suggested https://gist.github.com/1015151 ).

So all you need is to create a controller action that does a @user.trash! (I would put a bang on the trash) and the user is 'soft-deleted'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM