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.reload
和h.comments
。 从fine manual:
因此,您的关系应这样定义:
class Hotel
embeds_many :comments
end
class Comment
embedded_in :hotel
end
您应该说
belongs_to: hotel
时在Comment
中使用embedded_in :hotel
。该文档还说:
并且您的关系在一侧配置不正确,因此无法正常工作。
关于ruby-on-rails - 如何在Mongoid中保存embeds_many关系?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21139354/