Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple relations to the same model in Rails

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.

like image 705
Tim Sullivan Avatar asked Sep 18 '08 19:09

Tim Sullivan


2 Answers

in my case i have Asset and User model Asset can be create by an user and could be assigned to a user and User can create many assets and can have many Asset solution of my problem was asset.rb

class Asset < ActiveRecord::Base

belongs_to :creator ,:class_name=>'User'
belongs_to :assigned_to, :class_name=>'User' 

end

and

user.rb

class User < ActiveRecord::Base

has_many :created_assets, :foreign_key => 'creator_id', :class_name => 'Asset'
has_many :assigned_assets , :foreign_key => 'assigned_to_id', :class_name => 'Asset'

end

so your solution could be

class Course < ActiveRecord::Base
has_many :students ,:foreign_key => 'student_id', :class_name => 'Person'
has_many  :teachers, :foreign_key => 'teacher_id', :class_name => 'Person'

end

and

class Person < ActiveRecord::Base
belongs_to  :course_enrolled,:class_name=>'Course'
belongs_to  :course_instructor,:class_name=>'Course'

end
like image 185
Naveed Avatar answered Nov 04 '22 16:11

Naveed


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
like image 38
kch Avatar answered Nov 04 '22 15:11

kch