2011-11-17 48 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