【问题标题】:persist embeds_one relation mongoid坚持 embeds_one 关系 mongoid
【发布时间】:2013-03-19 17:53:44
【问题描述】:
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

我想用 user_detail 对象 embedded_in order 对象保存/持久化 mongodb 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

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 mongoid


    【解决方案1】:

    应该是:

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

    Order.new 对应于 OrderDetail.new

    【讨论】:

    • Uppss,谢谢,这是错误。我已编辑您的回复是UserDetail 而不是OrderDetail。谢谢!
    【解决方案2】:

    您不需要使用手动创建 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。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多