简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM