Skip to content

Latest commit

 

History

History
113 lines (83 loc) · 2.75 KB

README.textile

File metadata and controls

113 lines (83 loc) · 2.75 KB

acts_as_deleted

This plugin is based on the original acts_as_deleted plugin by kivanio.

What is it about?

A Rails plugin to enable soft deletion (with other words: hiding) of records.
Some fixes for callbacks (before_delete, after_delete, before_undelete, after_undelete)
were added. Additionally most of the parts have got tests now.

Installation:

script/plugin install git://github.com/chlu/acts_as_deleted.git
  • Create migrations for your models to add the acts_as_deleted columns
  • Add acts_as_deleted to your models

Examples:

In your migration (for a new record):

class CreateCars < ActiveRecord::Migration
  def self.up
    create_table :cars do |t|
      t.string :name

      # Use "deletestamps" to create columns "deleted" and "deleted_at"
      # With "true", a column "deleted_by" will be created to set an user id (e.g. with restful-authentication)
      t.deletestamps(true)
      
      t.timestamps
    end
  end

  def self.down
    drop_table :cars
  end
end

In your model:

class Car < ActiveRecord::Base
  # Use default named scopes: "only_deleted" and "without_deleted"
  acts_as_deleted

  # You can use callbacks for delete and undelete just like other active record callbacks
  after_delete :notify_someone

protected
  def notify_someone
    logger.info('Your car has been deleted. Ouch.')
  end
end

In your Controller:

class CarController < ApplicationController
  
  # Use scope "without_deleted" to find normal records
  def index
    @cars = Car.without_deleted
  end
  
  # In destroy action use "delete" method to hide a record
  def destroy
   @car = Car.find(params[:id])
    if @car.delete
      flash[:notice] = 'Bye Bye Car.'
    end
    redirect_to(cars_url)
  end
  
  # When you use plugin restful-authentication, you can use "delete_with_user" to save user
  def destroy_with_user
    @car = Car.find(params[:id])
    if @car.delete_with_user(current_user.id)
      flash[:notice] = 'Bye Bye Car.'
    end
    redirect_to(cars_url)
  end
  
  # A record can be undeleted
  def undelete
    @car = Car.find(params[:id])
    @car.undelete
  end
end

Tips:

To use validates_uniqueness_of with this plugin, you should use the option :scope of validates_uniqueness_of to prevent unique conflicts with deleted records.

validates_uniqueness_of :name, :scope => :deleted

The above example would validate “name AND deleted” instead of only “name”.

Copyright

Copyright © 2009 [Christopher Hlubek] http://www.resoap.com, released under the MIT license

Copyright © 2009 [Jan Schwenzien] http://www.code-schubser.de, released under the MIT license

Copyright © 2008 [Kivanio Barbosa] http://www.kivanio.com.br, released under the MIT license