假设我有两个模型,Classes和People.一个班级可能有一两个人作为教师,二十个人作为学生.因此,我需要在模型之间建立多种关系 - 一种是教师的1-> M,另一种是学生的1-> M.
编辑:教师和学生必须是一样的; 教师可以是其他班级的学生,反之亦然.
我确信这很容易,但谷歌并没有提出任何相关内容,我只是没有在我的书中找到它.
这里有很多选择,但假设教师总是教师,学生总是学生,你可以使用继承:
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
请记住,要使单表继承起作用,您需要type
在people
表中使用一列.
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
在我的情况下,我有资产和用户模型资产可以由用户创建,可以分配给用户,用户可以创建许多资产,可以有很多我的问题的资产解决方案是asset.rb
class Asset < ActiveRecord::Base belongs_to :creator ,:class_name=>'User' belongs_to :assigned_to, :class_name=>'User' end
和
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
所以你的解决方案可能是
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
和
class Person < ActiveRecord::Base belongs_to :course_enrolled,:class_name=>'Course' belongs_to :course_instructor,:class_name=>'Course' end