public
Description: An acts_as_paranoid like plugin which uses a boolean attribute to hide deleted records
Homepage:
Clone URL: git://github.com/fernandoluizao/acts_as_active.git
Fernando Luizao (author)
Sun Nov 01 07:47:30 -0800 2009
commit  c225d29534c0b979b80c93b34a426b52169bd442
tree    32bb00cddd8294f5d06c6a77d70f8bb2f6b4cd1a
parent  10d3da41b717a046ceb107d18235d21239d61bd3
README.rdoc

acts_as_active

This plugin override the default behavior of ActiveRecord#destroy method to set an active attribute to false instead of delete the record. The plugin also add a default_scope to hide the inactived records. This plugin assumes the table has a active boolean field, with default to true.

This plugin is HEAVLY influencied by acts_as_paranoid

Instalation

This plugin depends of default_scope, introduced in Rails 2.3. If you use Rails 2.1 or 2.2, install default_scope as a plugin:

  script/plugin install git://github.com/duncanbeevers/default_scope.git

After, install this plugin:

  script/plugin install git://github.com/fernandoluizao/acts_as_active.git

Example

  create_table :users do |t|
    t.string :name
    t.string :last_name
    t.boolean :active, :null => false, :default => true
  end

  class User
    acts_as_active
  end

  User.first.destroy
  UPDATE users SET active = 'f' WHERE id = 1

  User.first.destroy! #call the original destroy
  DELETE FROM users WHERE id = 1

  User.all
  SELECT * FROM users WHERE active = 't'

  User.all :conditions => {:name => "joe"}
  SELECT * FROM users WHERE (name = 'joe') AND (active = 't')

  User.find_with_inactive :conditions => {:name => "joe"}
  SELECT * FROM users WHERE (name = 'joe')

Methods added

Class Methods

acts_as_active(options = {})

  Turn on the plugin. options are:
    :with - name of the boolean field which indicates that the record is active. default is "active"
    :show_inactive_in_associations - if you want to show inactive objects in associations, set it to true

find_with_inactive(*args)

  Disable the default scope and invoke the default find
    args: the same of ActiveRecord::Base#find

all_with_inactive(*args)

  Disable the default scope and invoke the default all
    args: the same of ActiveRecord::Base#all

calculate_with_inactive(*args)

  Disable the default scope and invoke the default calculate
    args: the same of ActiveRecord::Base#calculate

count_with_inactive(*args)

  Disable the default scope and invoke the default count
    args: the same of ActiveRecord::Base#count

Instance Methods

active?

  Returns the active attribute

activate!

  Sets the active attribute to true

deactivate!

  Sets the active attribute to true

destroy!

  Calls the original destroy

Caveats

If you want to use default_scope in your model, add it AFTER the acts_as_active call. Example:

  class User
    acts_as_active
    default_scope :conditions => {:type => 'admin'}, :order => "name ASC"
  end

Copyright © 2009 Fernando Luizão, released under the MIT license