How to implement has_many :through relationships with Mongoid and mongodb?

前端 未结 4 757
猫巷女王i
猫巷女王i 2020-11-29 15:55

Using this modified example from the Rails guides, how does one model a relational \"has_many :through\" association using mongoid?

The challenge is that mongoid doe

4条回答
  •  猫巷女王i
    2020-11-29 16:48

    Just to expand on this, here's the models extended with methods that act very similar to the has_many :through from ActiveRecord by returning a query proxy instead of an array of records:

    class Physician
      include Mongoid::Document
      has_many :appointments
    
      def patients
        Patient.in(id: appointments.pluck(:patient_id))
      end
    end
    
    class Appointment
      include Mongoid::Document
      belongs_to :physician
      belongs_to :patient
    end
    
    class Patient
      include Mongoid::Document
      has_many :appointments
    
      def physicians
        Physician.in(id: appointments.pluck(:physician_id))
      end
    end
    

提交回复
热议问题