Reputation: 9327
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
?
Upvotes: 2
Views: 1683
Reputation: 626
You do not need post_id or belongs_to :post. Instead, you can use embedded_in :post. This will make a read method for _parent_reference named post so you can say comment.post instead of comment._parent_reference.
class Comment
include MongoMapper::EmbeddedDocument
embedded_in :post
end
Upvotes: 9
Reputation: 9327
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')>
Upvotes: 0