Time for action — getting paranoid

First let's include the Paranoia module:

class IAmParanoid
include Mongoid::Document
include Mongoid::Paranoia
end

That's it! Let's see the impact of this module:

irb> IAmParanoid.count
=> 0
irb> a = IAmParanoid.create
=> #<IAmParanoid _id: 4f22eca5fed0eb9dfc000001, _type: nil, deleted_at: nil>
irb> b = IAmParanoid.create
=> #<IAmParanoid _id: 4f22eca9fed0eb9dfc000002, _type: nil, deleted_at: nil>
irb> IAmParanoid.count
=> 2
irb> > a.remove
=> true
irb> IAmParanoid.count
=> 1
irb> a = IAmParanoid.deleted.first
=> #<IAmParanoid _id: 4f22eca9fed0eb9dfc000002, _type: nil, deleted_at: 2012-01-27 18:28:13 UTC>
irb> a.restore
=> 2012-01-27 18:28:13 UTC
irb> IAmParanoid.count
=> 2

What just happened?

When we added the Paranoia module, it added a field called deleted_at into the object.

irb> a = IAmParanoid.create
=> #<IAmParanoid _id: 4f22eca9fed0eb9dfc000002, _type: nil,
deleted_at: nil>

When we invoke the remove method, the deleted_at gets updated. Because the Paranoia module is included:

  • A field called deleted_at is added to the document.
  • A default criteria is added with the condition where(:deleted_at => nil).
  • A scope called deleted is added to where(:deleted_at.ne => nil).

Now, when we invoke any finder or criteria methods, we get all objects apart from the ones removed:

irb> a.remove
=> true
irb> IAmParanoid.count
=> 1

If we want to fetch the deleted objects, we can use the scope deleted:

irb> IAmParanoid.deleted.first
=> #<IAmParanoid _id: 4f22eca9fed0eb9dfc000002, _type: nil, deleted_at: 2012-01-27 18:28:13 UTC>

To restore the deleted objects, we can simply call restore.

Note

To really delete objects permanently from the database, even if we have included the Paranoia module, we can call either the destroy! or delete! methods.

Versioning

If we want to maintain the changes made to the objects, we can include the Versioning module.

This module embeds a versions object and maintains the versions for the object. By default, the latest version is returned for the object attributes. However, we can also fetch earlier versions of the object.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.165.126