简体   繁体   中英

Rails 4 filter has_many through

Given the following DoctorProfile model, how can I construct a query that filters DoctorProfile 's based on accepted insurances? I realize I can run the results through a block afterwards but I'd rather do this in a db query.

class DoctorProfile
  has_many :doctor_insurances
  has_many :accepted_insurances, -> { distinct }, through: :doctor_insurances, :source => :insurance_provider

class DoctorInsurance
  belongs_to :doctor_profile
  belongs_to :insurance_provider

Right now I have the following query and I'd like to be able to pass in either a single or multiple InsuranceProvider instances to filter out doctors whose accepted insurances are part of the array of insurance providers

DoctorProfile.where(:specialty_id => 1) 
DoctorProfile.where(doctor_insurances: {accepted_insurances: [instance]}).references(doctor_insurances: [:accepted_insurances])

应该可以解决这个问题,传递尽可能多的实例,它将在查询中进行。

也许您可以尝试以下方法:

DoctorProfile.joins(:accepted_insurances).where(doctor_insurances: {id: [instance]})

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