Overrides some basic Active Record methods for the current model so that calling #destroy sets a deleted_at field to the current timestamp.
Setup
Create migration file
acts_as_paranoid, by default, assumes the table has a deleted_at date/time field. Most normal model operations will work, but there will be some oddities.
Add the requestor to your model (app/models/widgets.rb)
123
classWidget<ActiveRecord::Baseacts_as_paranoidend
If you’d like to set a custom column for acts_as_paranoid just use the following options in your class method:
1
acts_as_paranoid:with=>'destroyed_at'
Use
12
Widget.find(:all)# => SELECT * FROM widgets WHERE widgets.deleted_at IS NULL
12
Widget.find(:first,:conditions=>['title = ?','test'],:order=>'title')# => SELECT * FROM widgets WHERE widgets.deleted_at IS NULL AND title = 'test' ORDER BY title LIMIT 1
12
Widget.find_with_deleted(:all)# => SELECT * FROM widgets
12
Widget.find(:all,:with_deleted=>true)# => SELECT * FROM widgets
12
Widget.find_with_deleted(1).deleted?# => Returns true if the record was previously destroyed, false if not
12
Widget.count# => SELECT COUNT(*) FROM widgets WHERE widgets.deleted_at IS NULL
12
Widget.count['title = ?','test']# => SELECT COUNT(*) FROM widgets WHERE widgets.deleted_at IS NULL AND title = 'test'
12
Widget.count_with_deleted# => SELECT COUNT(*) FROM widgets
12
Widget.delete_all# => UPDATE widgets SET deleted_at = '2013-08-15 13:01:59'
12
Widget.delete_all!# => DELETE FROM widgets
12
@widget.destroy# => UPDATE widgets SET deleted_at = '2013-08-15 13:01:59' WHERE id = 1
12
@widget.destroy!# => DELETE FROM widgets WHERE id = 1
12
@widget.recover!# => UPDATE widgets SET deleted_at = NULL WHERE id = 1