Ruby on Rails: Model Association with multiple foreign keys

半世苍凉 提交于 2019-11-29 05:18:40

You should separate out the teacher_student_links association into two associations:

  has_many :teacher_links, :foreign_key => :student_id, :dependent => :destroy, :class_name => "TeacherStudentLink"
  has_many :student_links, :foreign_key => :teacher_id, :dependent => :destroy, :class_name => "TeacherStudentLink"
  has_many :students, :through => :student_links
  has_many :teachers, :through => :teacher_links

You might need to add the foreign keys to the belongs_to association on TeacherStudentLink also

Update:

Regarding your second question about creating links, the following should work:

@user = User.find(params[:id])
@user.students << current_user

The TeacherStudentLink should be created automatically, and your associations should work if everything is set up correctly.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!