How to maintain embeds_many relation in 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

   => []

option 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

   => []
+4
source share
1 answer

I see two possible problems:

  • Hotel.lastoptionally Hotel52d68dd47361731d8b000000. You must look at h.commentsor be paranoid, h.reloadand h.comments.
  • Your associations are confusing.

From the exact guide :

Built-in 1-n

From one to many relationships in which children are embedded in the parent document are defined using Mongoid embeds_manyand embedded_inmacros.

Definition

embeds_many , n , , embedded_in.

, :

class Hotel
  embeds_many :comments
end

class Comment
  embedded_in :hotel
end

belongs_to: hotel Comment, embedded_in :hotel.

, :

.

, .

+4

All Articles