Mongoid::Versioning - delete one version

放肆的年华 提交于 2019-12-11 18:35:45

问题


I've a Rails model set up with Mongoid::Versioning.

class Post
  include Mongoid::Document
  include Mongoid::Timestamps

  include Mongoid::Versioning

  field :name, type: String
end

I want to delete a specific older version. For eg.

post = Post.create name: 'A'
post.update_attributes name: 'B'
post.update_attributes name: 'C'
post.version #=> 3
post.versions.count #=> 2
first_version = post.versions.first #=> #<Post _id: , created_at: _, updated_at: _, version: 2, name: "B">

I want to delete first_version, but when I try to delete it..

first_version.delete
post.versions.count #=> 1
post.reload
post.versions.count #=> 0

..all versions get deleted.

I've tried using destroy instead, tried running the code inside a block passed to post.versionless, to no avail. What should I do?

UPDATE: I've gotten it to work with Mongoid::Paranoia. But it'd be nice to have the flexibility of not using Mongoid::Paranoia.


回答1:


The concept of deleting intermediate versions is incorrect and corrupts the case for versioning. If you delete intermediate versions, then you are never sure if it's intentional or some corruption.

In spite of this, if you really want to do this, you should change to code to the following.

deleted = post.versions.first
post.versions.delete(deleted)

I am not sure why you want to do this though. If you want to ensure that you don't have too many versions and want to clean up, use max_versions class method.

Post.max_versions(5)

If you want to avoid versioning in some cases, use versionless

post.versionless(&:save)


来源:https://stackoverflow.com/questions/26770616/mongoidversioning-delete-one-version

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!