如何在连接模型上编写“范围”?

时间:2011-06-14 21:12:02

标签: ruby-on-rails-3

假设我有这些模型:Physician通过Patients有很多Appointments

class Physician < ActiveRecord::Base
  has_many :appointments
  has_many :patients, :through => :appointments
end
 
class Appointment < ActiveRecord::Base
  belongs_to :physician
  belongs_to :patient
end
 
class Patient < ActiveRecord::Base
  has_many :appointments
  has_many :physicians, :through => :appointments
end

我想写一个范围或类似的东西,这样我就可以找到一位确认任命的医生的所有患者。

最常用的方法是什么?

1 个答案:

答案 0 :(得分:1)

使用has_many:通过关联:

执行此操作
has_many :confirmed_patients, :through => :appointments, :source => :patient, :class_name => 'Patient', :conditions => { :confirmed => true }