Ruby On Rails - many to many between the same table

前端 未结 1 1472
一个人的身影
一个人的身影 2021-01-03 15:40

I am trying to create a somewhat complex relationship in Rails, and am having some trouble finding the best way to do so. I have a Users table in which each user acts as a t

相关标签:
1条回答
  • 2021-01-03 16:09

    you should be able to setup an assignment model and use it as you would any other many-to-many relationship:

    class User < ActiveRecord::Base
      has_many :student_teacher_assignments, :class_name => "StudentTeacherAssignment", :foreign_key => "student_id"
      has_many :teachers, :through => :student_teacher_assignments
      has_many :teacher_student_assignments, :class_name => "StudentTeacherAssignment", :foreign_key => "teacher_id"
      has_many :students, :through => :teacher_student_assignments
    end
    
    class StudentTeacherAssignment < ActiveRecord::Base
      belongs_to :student, :class_name => "User"
      belongs_to :teacher, :class_name => "User"
    end
    

    I would change the names of the assignments to be a little less similar and more meaningful, but the concept should remain the same

    0 讨论(0)
提交回复
热议问题