2011-11-17 51 views
5

我有以下的用戶模型創建一個新文檔,嵌入類型模型,MongoDB的 - 在一個嵌入式陣列

class User 
    include Mongoid::Document 
    include BCrypt 

    field :email,   :type => String 
    field :password_hash, :type => String 
    field :password_salt, :type => String 

    embeds_many :categories 
    embeds_many :transactions 
    .... 
    end 

我的問題是,我才發現,如果我使用的代碼:

me = User.where("some conditions") 
me.categories << Category.new(:name => "party") 

一切工作正常,但如果我用.create方法:

me = User.where("some conditions") 
me.categories << Category.create(:name => "party") 

我會得到一個異常:

undefined method `new?' for nil:NilClass 

任何人都知道這是爲什麼?從mongoid.org http://mongoid.org/docs/persistence/standard.html,我可以看到.new和.create實際上會生成相同的mongo命令。

需要幫助,謝謝:)

回答

10

立即創建保存文件到mongo。由於類別文檔在另一個文檔中(如嵌入),因此無法單獨保存。這就是爲什麼你收到錯誤。

爲了更加清楚起見,假設嵌入式文檔是包含子字段的父文件 文件中的字段。現在您可以輕鬆瞭解 您無法保存沒有文檔的字段。對?

反觀初始化文件類,並且將使用< <時,纔可以插入到文檔父。

Category.create(:name => "party") 
>>NoMethodError: undefined method `new?' for nil:NilClass 

相當於

c = Category.new(:name => "party") 
c.save 
>>NoMethodError: undefined method `new?' for nil:NilClass 

希望這有助於

+0

完全理解,非常清晰。 – larryzhao