我正在学习 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 列出与医生相关的所有患者。我怎样才能把预约时间也包括在内?一旦我有了患者列表,我就可以考虑查询约会,但我想知道是否有一种“rails”方式可以做到这一点(类似于 phycian. Patients_with_appointments )。如果没有,那么有效的方法是什么?
最佳答案
physician.appointments.includes(:patients).each do |appointment|
puts appointment.appointment_time
puts appointment.patient.name
end
**这未经测试
据我所知,您正在寻找的 Rails 方式并不真正存在。为了确保您不会在每个循环中加载每个循环,您可以使用包含。我不确定我是否将包含内容放在正确的位置,因为我目前无法访问 Rails 控制台。
如果有很多记录,您可能希望使用 find_each 批量查找,但对于您的示例来说,这应该可行。
关于ruby-on-rails - Rails 中查询多对多关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18050198/