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
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:
deleted_at
is added to the document. where(:deleted_at => nil)
. 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
.
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.
18.221.165.126