简体   繁体   中英

Rails filtering conditions on HABTM join table

 class Physician < ActiveRecord::Base
   has_many :appointments
   has_many :patients, through: :appointments
 end

 class Appointment < ActiveRecord::Base
   belongs_to :physician
   belongs_to :patient
   scope :physicals, -> { where appointment_type: 'physical' }
 end

 class Patient < ActiveRecord::Base
   has_many :appointments
   has_many :physicians, through: :appointments
 end

How can I access a list of patients, for a physician, with physicals in a single query? And the inverse (patients that have a different appointments of a different type)? Can I then set this with something like physician.patients_with_physicals = [patient] ?

The below will allow you to get the patients of any type in a single query:

class Physician < ActiveRecord::Base
  has_many :appointments
  has_many :patients, through: :appointments

  def patients_with_appointment_of_type type
    self.patients.joins(:appointments)
      .where(:appointments => {:type => type})
  end
end

Where you wish to use physician.patients_with_physicals = [patient] how are you planning on filling in the other appointment data which I assume is required (time, etc)?

It's worth noting that type as a column is used by Rails to signify a model that uses single table inheritance (STI) and could cause you issues, so I would recommend using a different column name.

How can I access a list of patients, for a doctor, with physicals in a single query?

Use ActiveRecord Association Extensions :

#app/models/physician.rb
Class Physician < ActiveRecord::Base
    has_many :appointments
    has_many :patients, through: :appointments do
        def with(type)
           where(appointment_type: type)
        end
    end
end

#-> @doctor.patients.with("physicals")
#-> Patient #1 etc

Can you explain what you mean by:

patients that have a different appointments of a different type)?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM