我正在尝试在 Mongoid 上设置版本控制系统。我遇到了保存父对象时未保存新嵌入版本对象的问题:
class Version
include Mongoid::Document
embedded_in :memorable, :polymorphic => true
field :version_number, :type => Integer
end
class Post
include Mongoid::Document
embeds_many :versions, :as => :memorable
before_save :create_version
field :version, :type => Integer, :default => 1
def create_version
self.versions.build({:version_number => self.version})
self.version = version + 1
end
end
@post = Post.create(:content => "Hello there!")
@post.update_attributes(:content => "Back at you!")
@post.reload
@post.versions
=> []
有什么想法吗?我知道引用的关系需要一个 :autosave 选项来保存子项,但没有任何文档说明嵌入式子项需要这样做,并且当我尝试它时它没有解决问题。
最佳答案
事实证明,这是 mongoid 代码库中的一个错误(在我看来),它会阻止在保存父级关联时保存名为“versions”的子级关联。
这是在 Mongoid::Hierarchy::InstanceMethods 中
def _children
relations.inject([]) do |children, (name, metadata)|
children.tap do |kids|
if metadata.embedded? && name != "versions"
child = send(name)
child.to_a.each do |doc|
kids.push(doc).concat(doc._children)
end unless child.blank?
end
end
end
end
我为此在 github 上创建了一个问题: https://github.com/mongoid/mongoid/issues/904
关于ruby-on-rails - Mongoid 没有在parent.save 上保存我的embeds_many child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5889324/