多个自引用has_many:通过Rails中的关联4。

时间:2016-12-07 22:53:23

标签: ruby-on-rails ruby activerecord associations

我正在编写一些使用多个自引用模型的代码,我希望能够使用连接表进行匹配,因为它们通过它相关联。

模型看起来像

User.rb:

class User < ActiveRecord::Base
  has_many :appointments
  has_many :students, through: :appointments
  has_many :teachers, through: :appointments
end

Appointment.rb:

class Appointment < ActiveRecord::Base
  belongs_to :student, class_name: User
  belongs_to :teacher, class_name: User
end

不幸的是,Rails生成的查询是:

SELECT "users".* FROM "users" INNER JOIN "appointments" ON "users"."id" = "appointments"."student_id" WHERE "appointments"."user_id" = $1

会抛出错误,因为约会没有user_id参数。

我已经尝试过指定foreign_key选项,但这没有做任何事情。我能用其他任何方式优雅地解决这个问题吗?

非常感谢你。

1 个答案:

答案 0 :(得分:3)

我设法解决了这个问题。 has_many:through所基于的has_many必须设置foreign_key选项。代码变成了:

class User < ActiveRecord::Base
  has_many :appointments_as_student, foreign_key: :student_id, class_name: Appointment
  has_many :appointments_as_teacher, foreign_key: :teacher_id, class_name: Appointment

  has_many :students, through: :appointments_as_teacher
  has_many :teachers, through: :appointments_as_student
end

感谢大家的努力。