Moorberry
August 15, 2013

Rails 2 and acts_as_paranoid

Posted on August 15, 2013  •  2 minutes  • 304 words
Table of contents

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.

$ script/server generate migration deleted_at:datetime

And then modify your migration file (app/db/migrations/000000000000_add_deleted_at…rb)to look something like:

class AddDeletedAtToWidgets < ActiveRecord::Migration
  def self.up
    add_column :widgets, :deleted_at, :datetime, :null => true
  end

  def self.down
    remove_column :widgets, :deleted_at
  end
end

Add the gem source to your Gemfile (app/Gemfile)

gem 'acts_as_paranoid', :git => 'git://github.com/technoweenie/acts_as_paranoid.git', :branch => 'integration_gem'

Run bundler

$ bundle install

Add the requestor to your model (app/models/widgets.rb)

class Widget < ActiveRecord::Base
  acts_as_paranoid
end

If you’d like to set a custom column for acts_as_paranoid just use the following options in your class method:

acts_as_paranoid :with => 'destroyed_at'

Use

Widget.find(:all)
# => SELECT * FROM widgets WHERE widgets.deleted_at IS NULL
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
Widget.find_with_deleted(:all)
# => SELECT * FROM widgets
Widget.find(:all, :with_deleted => true)
# => SELECT * FROM widgets
Widget.find_with_deleted(1).deleted?
# => Returns true if the record was previously destroyed, false if not 
Widget.count
# => SELECT COUNT(*) FROM widgets WHERE widgets.deleted_at IS NULL
Widget.count ['title = ?', 'test']
# => SELECT COUNT(*) FROM widgets WHERE widgets.deleted_at IS NULL AND title = 'test'
Widget.count_with_deleted
# => SELECT COUNT(*) FROM widgets
Widget.delete_all
# => UPDATE widgets SET deleted_at = '2013-08-15 13:01:59'
Widget.delete_all!
# => DELETE FROM widgets
@widget.destroy
# => UPDATE widgets SET deleted_at = '2013-08-15 13:01:59' WHERE id = 1
@widget.destroy!
# => DELETE FROM widgets WHERE id = 1
@widget.recover!
# => UPDATE widgets SET deleted_at = NULL WHERE id = 1
comments powered by Disqus
Follow me

I work on web & mobile application development, data integration, and AI.