views:

584

answers:

1

Let's say I have two models, Classes and People. A Class might have one or two People as instructors, and twenty people as students. So, I need to have multiple relationships between the models -- one where it's 1->M for instructors, and one where it's 1->M for students.

Edit: Instructors and Students must be the same; instructors could be students in other classes, and vice versa.

I'm sure this is quite easy, but Google isn't pulling up anything relevant and I'm just not finding it in my books.

+10  A: 

There are many options here, but assuming instructors are always instructors and students are always students, you can use inheritance:

class Person < ActiveRecord::Base; end  # btw, model names are singular in rails
class Student < Person; end
class Instructor < Person; end

then

class Course < ActiveRecord::Base  # renamed here because class Class already exists in ruby
  has_many :students
  has_many :instructors
end

Just remember that for single table inheritance to work, you need a type column in the people table.

using an association model might solve your issue

class Course < ActiveRecord::Base
  has_many :studentships
  has_many :instructorships
  has_many :students,    :through => :studentships
  has_many :instructors, :through => :instructorships
end

class Studentship < ActiveRecord::Base
  belongs_to :course
  belongs_to :student, :class_name => "Person", :foreign_key => "student_id"
end

class Instructorship < ActiveRecord::Base
  belongs_to :course
  belongs_to :instructor, :class_name => "Person", :foreign_key => "instructor_id"
end
kch
Hey, that's pretty clever, but unfortunately, someone could be both an instructor and a student, so I don't think this will work as-is.
Tim Sullivan
Ah, just saw your edit! Fantastic!
Tim Sullivan