2
votes

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 teacher and a student. I would like to have a has_many "students" (which are also just Users) and a has_many "teachers" (which are also just Users). I do not want to do any subclassing or single table inheritance. I just want two different many_to_many's between Users. What is the best way to do this? Is this a bad idea to do? Is there a better solution?

1
This is not a bad idea, and you would follow the standard stuff for many-to-many but use the same class instead of a different one. There is a modifier for the relationship called :class_name or :class.Dan Rosenstark

1 Answers

8
votes

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