views:

42

answers:

1

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?

+2  A: 

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

Geoff Lanotte
Ahhh, Thats pretty much what I was trying to do, but I was getting it slightly wrong. This works great. Thanks!
Joe Cannatti