【问题标题】:How to save embeds_many relation in Mongoid?如何在 Mongoid 中保存 embeds_many 关系?
【发布时间】:2014-01-15 13:56:22
【问题描述】:
class Hotel
  include Mongoid::Document

  field :title, type: String

  embeds_many :comments
end

class Comment
  include Mongoid::Document

  field :text, type: String

  belongs_to :hotel

  validates :text, presence: true
end

h = Hotel.create('hotel') 

   => <#Hotel _id: 52d68dd47361731d8b000000, title: "hotel">

c = Comment.new(text: 'text')

   => <#Comment _id: 52d68f3d7361731d8b040000, text: "text", hotel_id: nil>

h.comments << c

   => [#<Comment _id: 52d68f3d7361731d8b040000, text: "text", hotel_id: nil>]
h.save

   => true
Hotel.last.comments

   => []

变体 2

h.comments << Comment.new(text: 'new', hotel_id: h.id)

   => [<#Comment _id: 52d68f3d7361731d8b040000, text: "text", hotel_id: nil>, <#Comment _id: 52d691e17361731d8b050000, text: "new", hotel_id: BSON::ObjectId('52d68dd47361731d8b000000')>]

h.save

   => true
Hotel.last.comments

   => []

【问题讨论】:

    标签: ruby-on-rails mongoid


    【解决方案1】:

    我看到两个可能的问题:

    1. Hotel.last 不一定是 Hotel 52d68dd47361731d8b000000。你应该看看h.comments 或偏执,h.reload 和h.comments。
    2. 您的关联很混乱。

    来自fine manual:

    嵌入式 1-n

    孩子嵌入在一对多关系中 父文档使用 Mongoid 的 embeds_many 和 embedded_in 宏。

    定义

    关系的父文档应该使用embeds_many宏 表示它有 n 个嵌入的子节点,其中文档 嵌入式使用embedded_in。

    所以你的关系应该这样定义:

    class Hotel
      embeds_many :comments
    end
    
    class Comment
      embedded_in :hotel
    end
    

    当你应该说embedded_in :hotel时,你在Comment中使用belongs_to: hotel。

    文档还说:

    关系的双方都需要定义才能正常工作。

    并且您的关系在一侧配置不正确,因此无法正常工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-10
      • 1970-01-01
      • 1970-01-01
      • 2011-08-16
      • 1970-01-01
      • 2014-05-13
      • 1970-01-01
      相关资源
      最近更新 更多