活动记录查询以获取 rails 中嵌套关联的计数

Active record query to get the count for nested associations in rails

如何编写一个 ActiveRecord 查询来获取共享一个 appointmentpatients 的数量(physician 可以有多个 appointments

class Hospital < ActiveRecord::Base
  has_many :appointments
  has_many :patients
  has_many :physicians
end

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

class Appointment < ActiveRecord::Base
  belongs_to :physician
  belongs_to :patient
  belongs_to :hospital
end

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

我可以像Patient.first.hospital.appointments一样得到它。但确实需要编写一个干净的 activerecord 查询以及 hospital_id 不为 null

的地方

谢谢

据我了解,您想在某些条件下进行多个嵌套连接。这是如何干净地完成的:-

Patient.joins(:appointments => [:physician,:hospital]).where(patients:{<condition_hash_for_patient>},physicians:{<condition_hash_for_physician>},hospitals:{<condition_hash_for_hospital>})