Mongoid::Versioning - how to check previous versio

2019-07-23 05:21发布

问题:

I include the Mongoid::Versioning module in my Mongoid based class. What's the best way to check the previous 'version' or incarnation of a document? I want to be able to see its history. This can be either through rails console or MongoDB shell. What's the most easiest way to view the document history?

回答1:

The Mongoid::Versioning module adds a field named version of type Integer to the document, that field records the version of the current document, starting at 1, up to the maximum (if defined). In addition you will have an embedded document "versions" that will be created. There is then a before_save callback which takes care of the versioning for you.

Generally I would recommend a maximum, but that is up to you. In terms of how to get at them, well you didn't give an example document, so let's go with a very simple article as an example:

#Make an empty post, just a title, version 1
post = Post.create(:title => "Hello World")
# Now add some "content" and save, version 2
post.content = "Woo - content"
post.save

That will give us a document something like this:

{
  "title": "Hello World",
  "content": "Woo - content",
  "comments": [
  ]
  "version": 2
  "versions": [
    { "title": "Hello World", "version": 1 }
  ]
}

Now you just need to use your standard find mechanisms to get to it:

post = Post.find(:first, :conditions => {:title => "Hello World"})

Grab the latest version out of that, and then you can programmatically search for previous versions. I would post output, but I don't have a sample set up at the moment.

Similarly you need only run db.namespace.find() based on the title, version fields if you wish to do it via the shell.

Hopefully that makes sense.