2010-10-25 62 views
2

嵌入文档家长协会如果我有:使用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

回答

9

你不需要POST_ID或belongs_to的:岗位。相反,你可以使用embedded_in:post。这将为名为post的_parent_reference创建一个读取方法,以便您可以说comment.post而不是comment._parent_reference。

class Comment 
    include MongoMapper::EmbeddedDocument 

    embedded_in :post 
end 
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')>