这应该是多少:通过关系是多态的还是不是?

时间:2015-03-10 02:27:22

标签: ruby-on-rails activerecord

我通过TeachersClassroomshas_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_idclassroomable_type指向教师或学生。

2。)简化事情并将另一个外键添加到名为ClassroomMemberships的{​​{1}},在这种情况下,对于给定的行,student_idstudent_id将具有值。

哪个是更好的选择?

2 个答案:

答案 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属性,但最容易查询您的用例。

相关问题