2010-03-10 82 views
1

我有點卡在MongoMapper中的EmbeddedDocuments的概念。我的模型是這樣的:MongoMapper查找EmbeddedDocument

class Post 
    include MongoMapper::Document 

    many :categories 
    many :qualities 
end 

class Category 
    include MongoMapper::EmbeddedDocument 

    belongs_to :post 
    many :qualities 
end 

class Quality 
    include MongoMapper::EmbeddedDocument 
    key :category_id, ObjectId 

    belongs_to :post 
    belongs_to :category 
end 

我的問題是一種簡單的:我顯示一個帖子,並要列出它的類別和屬於它(CATEGORY_ID)所有的素質。

回答

0

post.categories.each do |cat| 
    puts cat 
    puts cat.qualities 
end 

之後它取決於如何將它保存到數據庫中,因爲每個EmbeddedDocument不需要belongs_to與他們的父級。每個文檔中都有_parent_document和_root_document來查看belongs_to。

+0

其實我在每個類別中都有一個品質數組,但它是空的。質量不是嵌入在類別中,而是嵌入在後。 – pex 2010-03-10 13:25:33

+0

那麼協會的品質如何與品類? – shingara 2010-03-10 13:33:43

+0

我認爲同一父母的兩個嵌入文檔也可能具有belongs_to/many關係。我將質量保存在category_id中。 – pex 2010-03-10 16:41:44