Mysql Rails活动记录,从has_many中获取相关记录:通过记录上的where子句的关系
我与Mysql Rails活动记录,从has_many中获取相关记录:通过记录上的where子句的关系,mysql,ruby-on-rails,activerecord,Mysql,Ruby On Rails,Activerecord,我与建立了关系,通过建立了许多关系 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
建立了关系,通过建立了许多关系
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
class医生
在预约角色等于PI或G2的情况下,如何为给定的医生获取所有患者
我尝试了内科医生.查找(50).预约.其中('role=?或role=?','PI','G2')。患者
编辑:
我从上面得到了未定义的方法。难道我不应该得到通关的相关记录吗?在medicine.find(50).appointment.where('role=?或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