Module: Mongoid::Paranoia

Extended by:
ActiveSupport::Concern
Defined in:
lib/mongoid/paranoia.rb

Overview

Include this module to get soft deletion of root level documents. This will add a deleted_at field to the Document, managed automatically. Potentially incompatible with unique indices. (if collisions with deleted items)

To use:

class Person
  include Mongoid::Document
  include Mongoid::Paranoia
end

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#delete!Object

Delete the paranoid Document from the database completely.

Example:

document.delete!



35
36
37
38
# File 'lib/mongoid/paranoia.rb', line 35

def delete!
  @destroyed = true
  Mongoid::Persistence::Remove.new(self).persist
end

#destroy!Object

Delete the paranoid Document from the database completely. This will run the destroy callbacks.

Example:

document.destroy!



26
27
28
# File 'lib/mongoid/paranoia.rb', line 26

def destroy!
  run_callbacks(:destroy) { delete! }
end

#destroyed?Boolean

Determines if this document is destroyed.

Returns:

true if the Document was destroyed.

Returns:



64
65
66
# File 'lib/mongoid/paranoia.rb', line 64

def destroyed?
  @destroyed || !!deleted_at
end

#remove(options = {}) ⇒ Object Also known as: delete

Delete the Document, will set the deleted_at timestamp and not actually delete it.

Example:

document.remove

Returns:

true



50
51
52
53
54
55
# File 'lib/mongoid/paranoia.rb', line 50

def remove(options = {})
  now = Time.now
  collection.update({ :_id => self.id }, { '$set' => { :deleted_at => Time.now } })
  @attributes["deleted_at"] = now
  true
end

#restoreObject

Restores a previously soft-deleted document. Handles this by removing the deleted_at flag.

Example:

document.restore



74
75
76
77
# File 'lib/mongoid/paranoia.rb', line 74

def restore
  collection.update({ :_id => self.id }, { '$unset' => { :deleted_at => true } })
  @attributes.delete("deleted_at")
end