加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 03:23:33 所属栏目:百科 来源:网络整理
导读:class Hotel include Mongoid::Document field :title,type: String embeds_many :commentsendclass Comment include Mongoid::Document field :text,type: String belongs_to :hotel validates :text,presence: trueendh = Hotel.create('hotel') = #Hotel
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,hotel_id: nil>]
h.save

   => true
Hotel.last.comments

   => []

变种2

h.comments << Comment.new(text: 'new',hotel_id: h.id)

   => [<#Comment _id: 52d68f3d7361731d8b040000,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:

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

你应该说embedded_in:hotel,你在评论中使用belongs_to:hotel.

文档还说:

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读