cjm2671
cjm2671

Reputation: 19476

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:

Upvotes: 0

Views: 516

Answers (2)

Rodrigo Flores
Rodrigo Flores

Reputation: 2461

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

Upvotes: 0

Carl Zulauf
Carl Zulauf

Reputation: 39558

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.

Upvotes: 2

Related Questions