lar*_*hao 5 mongodb mongoid ruby-on-rails-3
我有以下用户模型,嵌入了Category模型,
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
Run Code Online (Sandbox Code Playgroud)
我的问题是,我刚发现如果我使用代码:
me = User.where("some conditions")
me.categories << Category.new(:name => "party")
Run Code Online (Sandbox Code Playgroud)
一切正常,但如果我使用.create方法:
me = User.where("some conditions")
me.categories << Category.create(:name => "party")
Run Code Online (Sandbox Code Playgroud)
我会得到一个例外:
undefined method `new?' for nil:NilClass
Run Code Online (Sandbox Code Playgroud)
谁知道为什么会这样?从mongoid.org http://mongoid.org/docs/persistence/standard.html,我可以看到.new和.create实际上生成了相同的mongo命令.
需要帮助,谢谢:)
Ram*_*Vel 10
立即创建将文档保存到mongo中.由于类别文档位于另一个文档(嵌入式)中,因此无法单独保存.这就是为什么你得到错误.
为了更清楚,假设嵌入文档作为父文档中包含子字段的字段.现在,您可以轻松了解无法在没有文档的情况下保存字段.对?
另一方面新建 初始化文档类,并且只在使用<<时才会插入到父文档中.
Category.create(:name => "party")
>>NoMethodError: undefined method `new?' for nil:NilClass
Run Code Online (Sandbox Code Playgroud)
相当于
c = Category.new(:name => "party")
c.save
>>NoMethodError: undefined method `new?' for nil:NilClass
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助