题目有点拗口。请忽略。
下面是正题:
现在我有 3 个 model,分别是 Pyysician、Appointment、Patient;他们的关系如下:
class Physician < ActiveRecord::Base
has_many :appointments
has_many :patients, through: :appointments
has_many :healed_patients, -> { where(state: Patient::HEALED).order('appointments.created_at DESC')}, through: :appointments, class_name: 'Patient'
end
class Appointment < ActiveRecord::Base
belongs_to :physician
belongs_to :patient
belongs_to :healed_patient, class_name: 'Patient', foreign_key: 'patient_id'
end
class Patient < ActiveRecord::Base
HEALED = 1
has_many :appointments
has_many :physicians, through: :appointments
end
如果现在有 Physician 的一个实例physician
,用它调用physician.healed_patients
是可以正常工作的。如果使用Physician.includes(:healed_patients).last
,则会报错。
错误如下:
2.2.1 :001 > phy = Physician.last
Physician Load (0.1ms) SELECT "physicians".* FROM "physicians" ORDER BY "physicians"."id" DESC LIMIT 1
=> #<Physician id: 1, created_at: "2016-02-23 14:40:38", updated_at: "2016-02-23 14:40:38">
2.2.1 :002 > phy.healed_patients
Patient Load (0.2ms) SELECT "patients".* FROM "patients" INNER JOIN "appointments" ON "patients"."id" = "appointments"."patient_id" WHERE "appointments"."physician_id" = ? AND "patients"."state" = ? ORDER BY appointments.created_at DESC [["physician_id", 1], ["state", 1]]
=> #<ActiveRecord::Associations::CollectionProxy [#<Patient id: 1, state: 1, created_at: "2016-02-23 14:40:56", updated_at: "2016-02-23 14:40:56">]>
2.2.1 :003 > phy = Physician.includes(:healed_patients).last
Physician Load (0.2ms) SELECT "physicians".* FROM "physicians" ORDER BY "physicians"."id" DESC LIMIT 1
Appointment Load (0.7ms) SELECT "appointments".* FROM "appointments" WHERE "patients"."state" = ? AND "appointments"."physician_id" IN (1) [["state", 1]]
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: patients.state: SELECT "appointments".* FROM "appointments" WHERE "patients"."state" = ? AND "appointments"."physician_id" IN (1)
请问有什么方法解决 includes 的问题否 或者 我的这个写法哪里有问题? 谢谢诸位。谢谢