代码之家  ›  专栏  ›  技术社区  ›  agentofuser

使用MongoMapper的嵌入文档的父关联

  •  2
  • agentofuser  · 技术社区  · 15 年前

    class Post
      include MongoMapper::Document
    
      has_many :comments
    end
    

    如果我这样做:

    class Comment
      include MongoMapper::EmbeddedDocument
    
      belongs_to :post # relevant part
    end
    

    它是否使用 _root_document / _parent_document ,还是必须添加(多余的) key :post_id ?

    2 回复  |  直到 15 年前
        1
  •  9
  •   John Nunemaker    15 年前

    您不需要post_id或belongs_to:post。相反,您可以使用embedded_-in:post。这将为名为post的父引用创建一个read方法,这样您就可以说comment.post而不是comment。

    class Comment
      include MongoMapper::EmbeddedDocument
    
      embedded_in :post
    end
    
        2
  •  0
  •   agentofuser    15 年前

    确实需要 这个 post_id

    下面是我如何测试的(与问题中的类一样):

    > post = Post.new
     => #<Post _id: BSON::ObjectId('4cc5955ec2f79d4c84000001')>
    > comment = Comment.new
     => #<Comment _id: BSON::ObjectId('4cc59563c2f79d4c84000002')>
    > post.comments << comment
     => [#<Comment _id: BSON::ObjectId('4cc59563c2f79d4c84000002')>]
    > post.save
     => true
    > post.reload
     => #<Post _id: BSON::ObjectId('4cc5955ec2f79d4c84000001')>
    > comment = post.comments.first
     => #<Comment _id: BSON::ObjectId('4cc59563c2f79d4c84000002')>
    > comment.post
     => nil
    > class Comment
    ?>  key :post_id
    ?>  end
     => #<MongoMapper::Plugins::Keys::Key:0xb5ab0328 @name="post_id", @type=nil, @default_value=nil, @options={}>
    > comment
     => #<Comment post_id: nil, _id: BSON::ObjectId('4cc59563c2f79d4c84000002')>
    > comment.post
     => nil
    > comment.post = post
     => #<Post _id: BSON::ObjectId('4cc5955ec2f79d4c84000001')>
    > comment.save
     => true
    > comment.post
     => #<Post _id: BSON::ObjectId('4cc5955ec2f79d4c84000001')>
    
    推荐文章