开发者

Mongoid is not saving my embeds_many children on parent.save

I'm trying to setup a versioning system on Mongoid.开发者_如何学编程 I'm running into the problem that the new embedded version objects are not being saved when the parent object is saved:

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
=> []

Any thoughts? I know referenced relations require an :autosave option to save children, but none of the documentation states this is required for embedded children, and it didn't fix the problem when I tried it.


It turns out this is a bug (in my opinion) in the mongoid codebase that prevents child associations named "versions" from being saved when the parent is saved.

This is in 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

I've created an issue on github for this here: https://github.com/mongoid/mongoid/issues/904

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜