views:

27

answers:

1

This example makes it seem like both are used (included) in order to make a class a persistent model, but it is not clear when I should use one or the other.

+2  A: 

A MongoMapper::Document is saved to the database as a top-level record. A MongoMapper::EmbeddedDocument is saved within another document. For instance, let's say I have a blogging application. I have a Post and Comment model. They might look something like this:

require 'mongo_mapper'
MongoMapper.database = 'test'

class Post
  include MongoMapper::Document

  key :title
  key :body
  key :comments

  many :comments
end

class Comment
  include MongoMapper::EmbeddedDocument

  key :author
  key :body
end

p = Post.new(:title => 'Some post', :body => 'About something')
p.comments << Comment.new(:author => 'Emily', :body => 'A comment')

p.save

puts Post.all.map(&:inspect)

Will produce a document in your mongo database that looks like this:

{ "_id" : ObjectId("4c4dcf4b712337464e000001"),
  "title" : "Some post",
  "body" : "About something",
  "comments" : [
        {
                "body" : "A comment",
                "author" : "Emily",
                "_id" : ObjectId("4c4dcf4b712337464e000002")
        }
] }

In terms of interacting with them through MongoMapper, only a MongoMapper::Document response to methods like find and save. A MongoMapper::EmbeddedDocument can only be accessed through its parent document. The implication of this is that you should only use MongoMapper::EmbeddedDocument for models that are clearly subsidiary to their parent models and will only be used in the context of that parent.

Emily