Embeded document with belong_to association in Mongoid

前端 未结 2 1476
谎友^
谎友^ 2021-01-21 21:31

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 mo

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-21 22:31

    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
    

提交回复
热议问题