在Mongoid中嵌入带有belong_to关联的文档 [英] Embeded document with belong_to association in Mongoid
问题描述
我有像波纹管这样的模型.我想通过来宾列表"为具有不同状态的用户查询事件.如果客人输入的清单没有错,则应将其嵌入事件中吗?如果我的模型设计错误,我会开放其他解决方案.
I have models like bellow. i want to query events for user with different kind of statuses by guests 'list'. If am not wrong guests list should be embeded in events? If my model design are wrong i`m open for different solution.
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
中,您仅将信息保留在仅父文档中需要的嵌入式文档中.
The model structure is wrong as in Mongo
you only keep the information in embedded documents which are required only in parent document.
如果在来宾中只有状态字段,则可以尝试此操作,例如,两种状态类型存在或不存在
If in guests you have only status field, then you can try this,e.g., two status type present or not present
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
然后您可以使用类似状态的查询
then you can query with the status like
Event.first.present_guests
这篇关于在Mongoid中嵌入带有belong_to关联的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!