ruby-on-rails - Mongoid 中具有 Belongs_to 关联的嵌入文档

标签 ruby-on-rails mongodb mongoid

我有如下所示的模型。我想按客人“列表”查询具有不同状态的用户的事件。如果我没记错的话,嘉宾名单应该嵌入到事件中吗?如果我的模型设计错误,我愿意接受不同的解决方案。

class User
  include Mongoid::Document

end

class Events
  include Mongoid::Document

  embeds_many :guests
end

Class Guests
  include Mongoid::Document

  embed_in :event
  belongs_to :user

  field :status

end

最佳答案

模型结构是错误的,因为在 Mongo 中,您只将信息保留在嵌入文档中,而这些信息仅在父文档中需要。

如果在 guest 中您只有状态字段,那么您可以尝试此操作,例如存在或不存在两种状态类型

class User
  include Mongoid::Document
  has_and_belongs_to_belongs_to :event, :inverse_of => "present_guests"
  has_and_belongs_to_belongs_to :event, :inverse_of => "not_present_guests"
end

class Event
  include Mongoid::Document
  has_and_belongs_to_many :present_guests, :class_name => "User", :inverse_of => "present_guests"
  has_and_belongs_to_has_many :not_present_guests, :class_name => "User", :inverse_of => "not_present_guests"
end

然后你可以查询类似的状态

Event.first.present_guests

关于ruby-on-rails - Mongoid 中具有 Belongs_to 关联的嵌入文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17935525/

相关文章:

ruby-on-rails - 为什么必须使用 fetch 获取 Rails 参数?

arrays - mongoid 更新数组中的元素

ruby - Mongoid 还是 MongoMapper?

ruby-on-rails - Mongoid 批量收集插入 : how to get the ids of the newly created items?

ruby-on-rails - Rails 字符串助手删除连字符并大写?

ruby-on-rails - 如何在辅助模块中定义的模型类中使用方法

ruby-on-rails - Rails rake 任务是否提供对 ActiveRecord 模型的访问?

mongodb - 仅当 MongoDB 文档字段不存在时,如何更新它们?

java - 使用 objectID 对嵌套对象进行 MongoDB java 驱动程序查询不起作用

node.js - mongodb 原生的 promise