Ruby on Rails - Many of the Many Between the Same Table

I am trying to create a somewhat complicated relationship in Rails, and I have some problems finding the best way to do this. I have a Users table in which each user acts as a teacher and student. I would like to have has_many β€œstudents” (who are also β€œUsers”) and β€œteachers” has_many (who are also β€œUsers”). I do not want to do any subclassical or unidirectional inheritance. I just need two different users. What is the best way to do this? It is a bad idea? Is there a better solution?

0
source share
1 answer

you should be able to customize the assignment model and use it just like 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 assignment names to be somewhat less similar and more meaningful, but the concept should remain the same

+5
source

Source: https://habr.com/ru/post/1710347/


All Articles