我正在编写一些使用多个自引用模型的代码,我希望能够使用连接表进行匹配,因为它们是通过连接表关联的。
模型看起来像
用户.rb:
class User < ActiveRecord::Base
has_many :appointments
has_many :students, through: :appointments
has_many :teachers, through: :appointments
end
约会.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
这会引发错误,因为 Appointment 没有 user_id 参数。
我已经尝试指定 foreign_key
选项,但这没有任何作用。还有其他方法可以优雅地解决这个问题吗?
非常感谢。
最佳答案
我已经设法解决了。 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
感谢大家的努力。
关于ruby-on-rails - 多重自引用 has_many :through associations in Rails 4.,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41028835/