ruby-on-rails - 多重自​​引用 has_many :through associations in Rails 4.

标签 ruby-on-rails ruby activerecord associations

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

模型看起来像

用户.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/

相关文章:

ruby-on-rails - 使用 ruby​​ 进行情感分析

ruby-on-rails - Rails has_many :through with :primary_key

ruby-on-rails - ActiveRecord 参数错误 : negative string size (or size too big)

ruby-on-rails - Rails 验证类型日期?

ruby-on-rails - 如何在 Capybara 中获取父节点?

ruby-on-rails - 如何在Rails离线应用程序中分发 ruby ?

ruby-on-rails - 将 form_for 标签与 get 方法一起使用

ruby-on-rails - 使用 slim 输出多行 html

ruby-on-rails - 只有付费的人才能注册申请...?

ruby-on-rails - Ruby on Rails 服务器在重新启动之前不会反射(reflect)对数据库记录的更改