与Rails中的同一模型的多重关系
时间:2020-03-06 14:23:05 来源:igfitidea点击:
假设我有两个模型,分别是Class和People。一个班级可能有一个或者两个人作为讲师,二十个人作为学生。因此,我需要在模型之间建立多种关系-对于教师来说,一种关系是1-> M,对于学生来说,一种关系是1-> M。
编辑:导师和学生必须相同;讲师可以是其他班级的学生,反之亦然。
我敢肯定,这很容易,但是Google并没有收集任何相关内容,我只是在书中找不到它。
解决方案
这里有很多选择,但是假设讲师始终是讲师,而学生始终是学生,则可以使用继承:
class Person < ActiveRecord::Base; end # btw, model names are singular in rails class Student < Person; end class Instructor < Person; end
然后
class Course < ActiveRecord::Base # renamed here because class Class already exists in ruby has_many :students has_many :instructors end
请记住,要使单个表继承起作用,我们需要在" people"表中有一个" type"列。
使用关联模型可能会解决问题
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