我正在学习Rails,但遇到了查询问题。我的模型具有多对多关系。很难解释我所使用的模型,因为它们对我的工作领域来说太具体了,因此我将使用来自rails guide的示例进行一些修改。
这是模型:
class Physician < ActiveRecord::Base
has_many :appointments
has_many :patients, through: :appointments
end
class Appointment < ActiveRecord::Base
attr_accessor :appointment_time
belongs_to :physician
belongs_to :patient
end
class Patient < ActiveRecord::Base
attr_accessor :name, :age
has_many :appointments
has_many :physicians, through: :appointments
end
我想要一个带有其Appointment.appointment_time的患者列表。我可以使用列出与医师相关的所有患者physician.patients
。我如何也可以包括约会时间?有了患者列表后,我可以想到查询约会,但是我想知道是否有“跟踪”方式(类似physician.patients_with_appointments
)。如果没有,执行此操作的有效方法是什么?
physician.appointments.includes(:patients).each do |appointment|
puts appointment.appointment_time
puts appointment.patient.name
end
**未经测试
据我所知,您正在寻找的Rails方式并不存在。为了确保没有在每个循环中加载每个循环,可以使用一个include。我不确定是否将包含项放在正确的位置,因为目前我无法使用Rails控制台。
如果有很多记录,您可能想使用find_each批量查找,但是对于您的示例,这应该可以工作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句