0

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.
cjm2671
  • 18,348
  • 31
  • 102
  • 161
  • possible duplicate of [How to "soft delete" user with Devise](http://stackoverflow.com/questions/5140643/how-to-soft-delete-user-with-devise) – lucapette Nov 23 '11 at 11:13

2 Answers2

2

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.

Carl Zulauf
  • 39,378
  • 2
  • 34
  • 47
  • I wish i could comment, but in agreement with Carl, here is much of the code you would need: http://stackoverflow.com/questions/5140643/how-to-soft-delete-user-with-devise – Alex Marchant Nov 23 '11 at 11:06
0

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

Rodrigo Flores
  • 2,411
  • 18
  • 17