0

这个例子看起来好像两者都被使用(included)以使一个类成为一个持久模型,但我不清楚何时应该使用其中一个。

4

1 回答 1

2

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.

于 2010-07-26T18:14:47.540 回答