Mongoid Versioning
Installation
Add this line to your application's Gemfile:
gem 'mongoid_versioning'
And then execute:
$ bundle
Or install it yourself as:
$ gem install mongoid_versioning
Usage
Include the MongoidVersioning::Versioned
module into your model:
class MyVersionedDocument
include Mongoid::Document
include MongoidVersioning::Versioned
end
Your class will then have:
field :_version, type: Integer
field :_based_on_version, type: Integer
Creating versions
To create new version of your document:
doc = MyVersionedDocument.new
doc.revise # => true
doc._version # => 1
doc._based_on_version # => nil
The #revise
method validates the document and runs :revise
, :save
and :update
callbacks (resp. :revise
, :save
and :create
for new record).
Retrieving versions
To access all previous versions:
doc.previous_versions # => Mongoid::Criteria
These versions are stored in separate collection, by default named by appending .versions
to name of the source collection. In the above example it is my_versioned_documents.versions
.
To access latest version (as stored in the db):
doc.latest_version # => MyVersionedDocument
To retrieve all versions of a document:
doc.versions # => Array
To retrieve specific version:
doc.version(2) # => MyVersionedDocument
Further Reading
See Further Thoughts on How to Track Versions with MongoDB.
Contributing
- Fork it ( https://github.com/tomasc/mongoid_versioning/fork )
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create a new Pull Request