2010-10-25 29 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')>