【问题标题】:Parent association for embedded document using MongoMapper使用 MongoMapper 嵌入文档的父关联
【发布时间】:2010-10-25 14:30:19
【问题描述】:

如果我有:

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

【问题讨论】:

    标签: mongomapper


    【解决方案1】:

    您不需要 post_id 或 belongs_to :post。相反,您可以使用 embedded_in :post。这将为 _parent_reference 命名的帖子创建一个读取方法,因此您可以说 comment.post 而不是 comment._parent_reference。

    class Comment
      include MongoMapper::EmbeddedDocument
    
      embedded_in :post
    end
    

    【讨论】:

      【解决方案2】:

      确实需要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')>
      

      【讨论】:

        猜你喜欢
        • 2010-12-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多