gpt4 book ai didi

ruby-on-rails - Mongoid 中带有 belongs_to 关联的嵌入式文档

转载 作者:可可西里 更新时间:2023-11-01 10:01:12 25 4
gpt4 key购买 nike

我有像下面这样的模型。我想通过客人“列表”查询具有不同状态的用户的事件。如果没有错,客人名单应该嵌入到事件中吗?如果我的模型设计有误,我愿意接受不同的解决方案。

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 中,您只将信息保留在嵌入文档中,而这些信息仅在父文档中需要。

如果在客人中你只有状态字段,那么你可以试试这个,例如,两种状态类型存在或不存在

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com