![](/img/trans.png)
[英]Rails / Active Record has_many through association - fetching a record
[英]Rails Active Record, get related record from has_many :through relationship with where clause on through record
我與has_many :through
建立了關系。
class Physician < ActiveRecord::Base
has_many :appointments
has_many :patients, through: :appointments
end
class Appointment < ActiveRecord::Base
belongs_to :physician
belongs_to :patient
# physician_id, patient_id
end
class Patient < ActiveRecord::Base
has_many :appointments
has_many :physicians, through: :appointments
end
在任命角色等於PI或G2的情況下,如何獲得給定醫師的所有患者?
我已經嘗試過Physician.find(50).appointments.where('role = ? or role = ?', 'PI', 'G2').patients
編輯:
我從上面得到未定義的方法。 我是否應該能夠獲得通行證的相關記錄? 在Physician.find(50).appointments.where('role = ? or role = ?', 'PI', 'G2')
,應該有一個appointments
方法,但沒有。
由於您希望患者對象返回,因此從該模型開始。 您想在約會和醫師上都添加WHERE子句,因此請加入這些關聯。 使用哈希表形式在where
引用聯接的表。
Patient.joins(:physician).
joins(:appointments).
where(appointments: {role: ["PI", "G2"]}).
where(physicians: {id: physician_id}).uniq
更新
考慮將范圍添加到模型中以供重復使用:
class Patient < ActiveRecord::Base
scope :for_physician, ->(physician_id) do
joins(:physicians).
where(physicians: {id: physician_id}
end
scope :for_roles, ->(roles) do
joins(:appointments).
merge(Appointment.for_roles(roles))
end
end
class Appointment < ActiveRecord::Base
scope :for_roles, ->(roles) do
where(role: roles)
end
end
然后你可以像這樣把它們放在一起
Patient.for_physician(50).for_roles(["PI", "G2"]).uniq
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.