Using acts_as_paranoid in your Rails app

Published on 18 July 2007 by James in Ruby

0

acts_as_paranoid (“AAP”) is a Ruby on Rails plugin that does not delete the row when destroy() is called. Rather, it sets a deleted_at field to a non-null value. The find() method is modified to skip any deleted records, thus making it easy to find only those rows that are considered active. You can locate previously deleted models by using the new find_with_deleted() method as you would any standard find() method.

Installing acts_as_paranoid

Having started a previous project without AAP, I opted to use it this time with Rails 1.2.3. I first tried installing the gem, but apparently that isn’t being kept compatible beyond Rails 1.1.6. After a quick Google, I found a Wiki page that describes the install procedure for the new Rails plugin. Word of warning: when you perform a svn export/checkout of the code, be sure to name the directory acts_as_paranoid, not acts_as_paranoid-x.y.z or you’ll get a “nil.empty?” error when starting your Rails app.

Using acts_as_paranoid

Now, it is simply a matter of adding a deleted_at datetime column to your model migration, adding acts_as_paranoid to your model, and then work with the model as you normally would. Here is an example unit test to demonstrate how to use it:

def test_delete_paranoid
    @my_model = my_models(:one)
    assert_not_nil @my_model
    @my_model.destroy
    @deleted = MyModel.find_with_deleted(:first, :conditions =>["id = ?",@my_model.id])
    assert_not_nil @deleted
    assert_equal @my_model.id, @deleted.id
    assert_not_nil @deleted.deleted_at
end

[tags]Ruby on Rails, plugins, acts_as_paranoid[/tags]

Leave a Reply