1
class Order
 include Mongoid::Document
 include Mongoid::Timestamps

 #relationships
  embeds_one :user_detail

  #fields
  field :description

  #validations  
  validates :user_detail, presence: true
end

这是按顺序嵌入的对象:

class UserDetail
  include Mongoid::Document
  include Mongoid::Timestamps

  #fields
  field :name, :type => String
  field :zip_code, :type => String
  field :email, :type => String

  # Relationships
  embedded_in :order

  #validations
  validates_presence_of :name, :zip_code, :email
end

order我想用user_detail对象对象保存/持久化 mongodbembedded_in order对象。

我尝试过:

order = Order.new(description: "checking description")
order.user_detail = Order.new(:name => "John", :zip_code => "26545", :email => "john@john.com")
order.save!

但我得到验证失败:

o.save!
Mongoid::Errors::Validations: 
Problem:
  Validation of Order failed.
Summary:
  The following errors were found: User detail is invalid
Resolution:
  Try persisting the document with valid data or remove the validations....

我该如何解决这个问题?我正在使用 mongoid 3.x

4

2 回答 2

2

应该:

order = Order.new(description: "checking description")
order.user_detail = UserDetail.new(:name => "John", :zip_code => "26545", :email => "john@john.com")
order.save!

Order.newOrderDetail.new

于 2013-03-19T17:56:33.453 回答
0

您不需要手动创建 user_detail 使用

order.user_detail = UserDetail.new... order.save!

如果您添加 autobuild 属性,嵌入的 user_detail 将自动创建

embeds_one :user_detail autobuild: true

如果您也想在数据库中保留 user_detail,请不要忘记添加

validates_presence_of :user_detail

否则您将不会在 mongo db 中看到持久化的 user_detail。

于 2016-12-07T05:42:58.360 回答