2010-10-25 22 views

Répondre

9

Vous n'avez pas besoin post_id ou belongs_to: poste. Au lieu de cela, vous pouvez utiliser embedded_in: post. Cela rendra une méthode de lecture pour _parent_reference nommée post afin que vous puissiez dire comment.post au lieu de comment.parent_reference.

class Comment 
    include MongoMapper::EmbeddedDocument 

    embedded_in :post 
end 
0

Vous avez besoin de la clé post_id.

Voilà comment je l'ai testé ce (avec les classes comme dans la question):

> 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')>