如何在Mongoid中保存embeds_many关系?

Sas*_*nik 5 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

   => []
Run Code Online (Sandbox Code Playgroud)

变种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

   => []
Run Code Online (Sandbox Code Playgroud)

mu *_*ort 6

我看到两个可能的问题:

  1. Hotel.last不一定是Hotel52d68dd47361731d8b000000.你应该看看h.comments或偏执,h.reload并且h.comments.
  2. 你的社团很困惑.

精细手册:

嵌入式1-n

将子项嵌入父文档中的一对多关系使用Mongoid embeds_manyembedded_in宏定义.

定义

关系的父文档应使用embeds_many宏来指示它具有n个嵌入的子级,嵌入的文档使用该子级embedded_in.

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

class Hotel
  embeds_many :comments
end

class Comment
  embedded_in :hotel
end
Run Code Online (Sandbox Code Playgroud)

您正在使用belongs_to: hotelComment时,你应该说的embedded_in :hotel.

文档还说:

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

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