我通过Teachers
为Classrooms
和has_many :through
建立了多对多关系设置:
class Teacher < ActiveRecord::Base
has_many :classrooms, :through => :classroom_memberships
end
class Classroom < ActiveRecord::Base
has_many :students
has_many :teachers, :through => :classroom_memberships
end
class ClassroomMemberships < ActiveRecord::Base
belongs_to :teacher
belongs_to :classroom
end
目前,Students
只能属于一个Classroom
:
class Student < ActiveRecord::Base
belongs_to :classroom
end
现在我需要跟踪学生的历史课堂会员资格,为教室创建第二个多对多关系。因此,虽然学生一次只能属于一个教室,但我需要知道去年,学生A属于教室B.
我想我有两个可行的选择:
1。)使classroom_memberships
关联具有多态性,因此我会有classroomable_id
和classroomable_type
指向教师或学生。
2。)简化事情并将另一个外键添加到名为ClassroomMemberships
的{{1}},在这种情况下,对于给定的行,student_id
或student_id
将具有值。
哪个是更好的选择?
答案 0 :(得分:0)
我可能会选择以下路线:
class Course < ActiveRecord::Base
# like "MATH 100"
has_many :sections
has_many :teachers, :through => :sections
end
class Term < ActiveRecord::Base
# like "Fall 2015"
has_many :sections
end
class Teacher < ActiveRecord::Base
has_many :sections
has_many :courses, :through => :sections
end
class Section < ActiveRecord::Base
# a course, in a term, taught by a teacher, with registered students
belongs_to :term
belongs_to :course
belongs_to :teacher
has_many :registrations
has_many :students, :through => :registrations
end
class Registration < ActiveRecord::Base
# a student in a specific section
belongs_to :section
belongs_to :student
end
class Student < ActiveRecord::Base
# a student's registrations are their course history
has_many :registrations
has_many :sections, through :registrations
end
首先,因为这是教育系统的一个相当基本的建模。
答案 1 :(得分:0)
听起来好像你想要一个ClassroomMembershipHistory模型。
像
这样的东西class ClassroomMembershipHistory < ActiveRecord::Base
belongs_to :student
belongs_to :classroom
end
使用year
属性,但最容易查询您的用例。