tags:

views:

15

answers:

2

If I have:

class Post
  include MongoMapper::Document

  has_many :comments
end

If I do:

class Comment
  include MongoMapper::EmbeddedDocument

  belongs_to :post # relevant part
end

Does that create an association using _root_document/_parent_document, or do I have to add the (redundant) key :post_id?

A: 

You do need the post_id key.

Here's how I tested this (with the classes as in the 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')>
obvio171