Embeded document with belong_to association in Mongoid

前端 未结 2 1475
谎友^
谎友^ 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:28

    I believe that model structure would work.

    Here's an example query to get all events with guests with the 'waiting' status:

    Events.where('guests.status' => 'waiting')
    

    Here's another example to, given an event, get all that event's guests with 'waiting' status:

    event = Events.first # get the desired event
    event.guests.where(:status => 'waiting')
    

    Finally, you should name your models singular names (User, Event, Guest). Also, your Guest model has some typos I fixed below:

    class User
      include Mongoid::Document
    
    end
    
    class Event
      include Mongoid::Document
    
      embeds_many :guests
    end
    
    class Guest
      include Mongoid::Document
    
      embedded_in :event
      belongs_to :user
    
      field :status
    end
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题