ruby-on-rails - 如何在 Mongoid 中保存 embeds_many 关系?

标签 ruby-on-rails mongoid

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

   => []

最佳答案

我看到两个可能的问题:

  • Hotel.last不一定Hotel 52d68dd47361731d8b000000。你应该看看h.comments或偏执,h.reloadh.comments .
  • 你的联想很困惑。

  • 来自 fine manual :

    Embedded 1-n

    One to many relationships where the children are embedded in the parent document are defined using Mongoid's embeds_many and embedded_in macros.

    Defining

    The parent document of the relation should use the embeds_many macro to indicate it has n number of embedded children, where the document that is embedded uses embedded_in.



    所以你的关系应该这样定义:
    class Hotel
      embeds_many :comments
    end
    
    class Comment
      embedded_in :hotel
    end
    

    您正在使用 belongs_to: hotelComment什么时候该说 embedded_in :hotel .

    文档还说:

    Definitions are required on both sides to the relation in order for it to work properly.



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

    关于ruby-on-rails - 如何在 Mongoid 中保存 embeds_many 关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21139354/

    相关文章:

    ruby-on-rails - 安装 gitlab-5.0 时遇到问题。我无法完成安装

    ruby-on-rails - Mongoid 有 Map/Reduce 吗?

    ruby-on-rails - rails : Twitter Bootstrap Buttons when visited get black text color

    mysql - 表达这段代码的更简洁的方式是什么?

    ruby-on-rails - Mongoid - 阵列管理?插入唯一值,如果存在则删除值?

    MongoDB mongoid自引用关系

    ruby-on-rails - 将 Heroku Postgres 数据库从开发计划迁移到基本计划

    mongodb - Mongoid 没有服务器可用匹配首选项

    ruby-on-rails - Mongoid `group()` 条件

    mongodb - 虽然我在数据库中有记录,但它给出的是 "Mongoid::Errors::DocumentNotFound"