【问题标题】:Querying many-to-many association in Rails在 Rails 中查询多对多关联
【发布时间】:2013-08-05 03:33:07
【问题描述】:

我正在学习 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”方式来做到这一点(类似于physician.patients_with_appointments)。如果没有,那么有效的方法是什么?

【问题讨论】:

  • 你为什么不想使用'physician.patients.include(:appointments)'?
  • 请注意,您可能无法得到适用于您的特定代码的答案,因为您选择使用假代码示例。

标签: ruby-on-rails model associations


【解决方案1】:
physician.appointments.includes(:patients).each do |appointment|
  puts appointment.appointment_time
  puts appointment.patient.name
end

**这未经测试

据我所知,您正在寻找的 rails 方式并不存在。为了确保您没有在每个循环中加载每个循环,您可以使用包含。我不确定我是否将包含放在正确的位置,因为我目前无法访问 Rails 控制台。

如果有很多记录,您可能希望使用 find_each 批量查找,但对于您的示例,这应该可行。

【讨论】:

  • 这样更有意义,因为这样你也可以在预约时间点餐。
【解决方案2】:

正如 phil.ts 所说:

patients = physician.patients.include(:appointments)

会成功的。

现在当你这样做时:

patients.appointment

数据库不需要额外的查询,因为 rails 知道将它们包含在第一个查询中。

【讨论】:

  • patients.appointment 会出错,因为patients 是一个 ActiveRecord::Relation。您还包括 appointments 而不是 appointment,因此对于每位患者,您将有一系列预约,而不仅仅是一个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多