12

クエリを介して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テーブルには、appointment_dateという名前の列があります

特定の日に予約を入れている特定の医師からすべての患者を取得するにはどうすればよいですか?

4

1 に答える 1

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

Date.todayは何でも変更でき、医師はidまたはidの配列で指定されます。

次のこともできます。

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

編集:

references(:appointments)Rails 4以降では、where句で予定を使用するために、クエリに追加する必要があります。

于 2013-03-26T16:11:31.003 に答える