小编Sas*_*nik的帖子

如何在Mongoid中保存embeds_many关系?

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 …
Run Code Online (Sandbox Code Playgroud)

ruby-on-rails mongoid

5
推荐指数
1
解决办法
4417
查看次数

标签 统计

mongoid ×1

ruby-on-rails ×1