Rails 4过滤器has_many通过

时间:2015-12-01 02:21:52

标签: ruby-on-rails

鉴于以下DoctorProfile模型,如何根据已接受的保险构建过滤DoctorProfile的查询?我意识到我之后可以通过一个块来运行结果,但我宁愿在db查询中执行此操作。

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

现在我有以下查询,我希望能够传入一个或多个InsuranceProvider个实例,以过滤掉那些接受保险属于保险提供商一部分的医生< / p>

DoctorProfile.where(:specialty_id => 1) 

2 个答案:

答案 0 :(得分:1)

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

应该做的伎俩,传入任意数量的实例,它将在查询中执行。

答案 1 :(得分:1)

也许你可以试试这个:

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