class Delta include Mongoid::Document include Mongoid::Versioning field :name, type: String end
Let's see it in action:
irb> a = Delta.create
=> #<Delta _id: 4f22f748fed0eb9e6e000003, _type: nil, version: 1, name: nil>
irb> a.name = "First"
=> "First"
irb> a.save
=> true
irb> a
=> #<Delta _id: 4f22f748fed0eb9e6e000003, _type: nil, version: 2, name: "First">
irb> a.name = "Second"
=> "Second"
irb> a.save
=> true
irb> a
=> #<Delta _id: 4f22f748fed0eb9e6e000003, _type: nil, version: 3, name: "Second">
irb> a.revise!
=> true
irb> a
=> #<Delta _id: 4f22f748fed0eb9e6e000003, _type: nil, version: 4, name: "Second">
When we included the Versioning
module:
The model is now configured to update the version every time the object is saved. When it's created the first time, notice that the version number is set:
irb> a
=> #<Delta _id: 4f22f748fed0eb9e6e000003, _type: nil,
version: 1,
name: nil>
Every time, the object is saved, the version number is incremented and the versioned attributes (that is, all the fields in the document) get saved inside the versions
embedded object's array and the version
is incremented.
If we want to update the version without any changes, we can use the revise!
method.
Some more fancy stuff with versioning
If you want to save the document but don't want to version it, use the versionless
method. This temporarily disables versioning, for example, object.versionless(&:save)
.
If you want to see changes made to the object, use the :previous_changes
method.
If you want to see the versioned objects, use the :versions
method.
Notice, that we mentioned cyclic relationship. We saw this earlier in the embedded relations. For versioning, we need exactly one parent and many child documents of the same class embedded in it!
title
field of the Book
model? Book.first.title
. Book.first[:title]
. Book.first.read_attribute(:title)
. Book.first.get_title
. cascaded_callbacks
option do? recursively_embeds_many
in the Author
model not do? embeds_many
relation for Author
. child_authors
. parent_author
in the Author
model. author_count
in the Author
model. embedded_in
relation in the embedded Model? Mongoid::Document
. This is the only way Mongoid knows that the document is embedded in another document. Mongoid::EmbeddedDocument
is specified, we do not need this relation, otherwise we need it.3.145.115.237