2013-03-26 84 views
7

has_many通過查詢有一些問題。Rails has_many通過查詢取決於通過表屬性

使用這裏的例子:http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association

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 

的預約表有一欄名爲appointment_date

我怎麼會得到所有的患者從具有在給定日期的預約特定醫師?

回答

13
Patient.includes(:physicians, :appointments).where('physicians.id = ? AND appointments.appointment_date = ?', <id or ids array>, Date.today) 

其中Date.today可以隨時更改,而pysician由id或id數組指定。

你也可以這樣做:

physician = Physician.find(id) 
patients = physician.patients.includes(:appointments).where('appointments.appointment_date = ?', some_date) 

編輯:

在Rails 4和轉發,你需要添加references(:appointments)到查詢,以便在where子句中使用的約會。

+1

太棒了!非常感謝。 – Ghar 2013-03-26 16:25:48

+1

這不適合我的鐵軌4,我花了不少時間搜索並找到[此解決方案](http://stackoverflow.com/questions/18799934/has-many-through-how-do-you -access-join-table-attributes)for rails 4: – 2014-08-03 17:03:44

+1

是的,在rails 4中,你需要使用'references'來引用來自includes的表名。 – spullen 2014-08-04 12:59:48