【发布时间】:2015-03-10 02:27:21
【问题描述】:
我通过has_many :through 为Teachers 和Classrooms 设置了多对多关系:
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 添加另一个名为 student_id 的外键,在这种情况下,对于给定的行,student_id 或 teacher_id 都会有一个值。
哪个是更好的选择?
【问题讨论】:
标签: ruby-on-rails activerecord