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)

Examples:

Make a document paranoid.

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.

Examples:

Hard delete the document.

document.delete!


33
34
35
36
# File 'lib/mongoid/paranoia.rb', line 33

def delete!
  @destroyed = true
  Persistence::Operations.remove(self).persist
end

#destroy!Object

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

Examples:

Hard destroy the document.

document.destroy!


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

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

#destroyed?true, false

Returns If the document is destroyed.

Returns:

  • (true, false)

    If the document is destroyed.



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

def destroyed?
  @destroyed || !!deleted_at
end

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

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

Examples:

Soft remove the document.

document.remove

Parameters:

  • options (Hash) (defaults to: {})

    The database options.

Returns:

  • (true)

    True.



47
48
49
50
51
52
53
# File 'lib/mongoid/paranoia.rb', line 47

def remove(options = {})
  return super if embedded? && respond_to?(:version_max) && version_max
  now = Time.now
  collection.update({ :_id => id }, { '$set' => { :deleted_at => now } })
  @attributes["deleted_at"] = now
  true
end

#restoreObject

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

Examples:

Restore the document from deleted state.

document.restore


72
73
74
75
# File 'lib/mongoid/paranoia.rb', line 72

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