views:

200

answers:

4

I'm looking for a way to faux-delete rows from a table using Rails. The rows shouldn't show up in any normal .find() search except for when I want to show recently deleted items. I'm using an Activities table right now for management of such tasks, which stores the class, id and method performed on rows recently.

Is there a way to disable a row without actually removing it from the table. Kind of like how iTunes has the checkbox next to songs?

+2  A: 

You can create a deleted column in your tables. When something is deleted, instead of having the delete function send a DELETE FROM table WHERE blah = true statement, you simply do UPDATE table SET deleted = true WHERE blah = true. Then, when you're looking for something, always set the conditions to include deleted = false (or true, if you're looking for deleted items). Anything that isn't deleted will be returned, but you'll still have the information saved about the deleted items.

Jeff Rupert
I considered that, but it would be a real pain in the ass and would surely create some messy activerecord syntax. Consider that I'm querying active rows hundreds of times throughout the application, and querying deleted rows only once.
Bloudermilk
You can save the repetition by using named scopes and default_scope.
jonnii
+4  A: 

Have you taken look at acts_as_paranoid. Sounds like that should meet your needs.

Rob Di Marco
That's awesome! Thanks!
Bloudermilk
A: 

You could copy the data to a "deleted records table",but it looks like acts_as_paranoid or similar (also called soft-delete) is what you want.

Can you add database indices that include the condition that deleted is false for the ordinary queries?

What sort of queries are those "The rows shouldn't show up in any normal .find()" .. which find's are you using?

Stephan

Stephan Wehner
A: 

Similar to the deleted column above, but you can probably avoid the headaches on the rails side by using views.

Say you have backing_table, which contains a column hidden. Then, you can use CREATE VIEW view_table SELECT all_columns_but_hidden FROM backing_table WHERE hidden = false;

Your model is based on the view, and doesn't need to do anything special. You can hide things by UPDATE backing_table SET hidden = true WHERE conditions;

Tim C