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

时间:2010-10-25 14:30:20

标签: mongomapper

如果我有:

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 个答案:

答案 0 :(得分:9)

您不需要post_id或belongs_to:post。相反,您可以使用embedded_in:post。这将为_parent_reference命名post的read方法,因此你可以说comment.post而不是comment._parent_reference。

class Comment
  include MongoMapper::EmbeddedDocument

  embedded_in :post
end

答案 1 :(得分:0)

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