rails 多级 "through",数据库架构分层

rails multi-levels of "through", database schema layering

我的数据目前按以下方式构建。

州(即加利福尼亚州)"has_many" 学校, 学校 "has_many" 年级(即 8 年级或 9 年级), GRADE "has_many" 类(即艺术、历史、化学), 类 "has_many" 学生。

我的目标是从高级视图中获取低级细节,否则,我希望获得 STATE(结构中最高级别的组件)内的所有学生(数据结构中的最低分母)。什么是最简单和最有效的结构方式,这样我就可以有一个命令让所有学生都在一个州内,即 "State.find(name: "California").students"。

我尝试了两级 "through" 关联,但它似乎是有限的。

潜在的基本数据设计如下所示:

class State < ActiveRecord::Base
  has_many :schools
  has_many :students, through: :schools
end

# Links students to schools
class Enrollment < ActiveRecord::Base
  belongs_to :school
  belongs_to :student
  belongs_to :grade
end

class School < ActiveRecord::Base
  has_many :enrollments
  has_many :students, through: :enrollments
  has_many :grades
  has_many :subjects, through: :grades
  belongs_to :state
end

# Denotes a educational step as in 1st grade
class Grade
  belongs_to :school
  has_many :subjects
end

# We can't use Class since it clashes with the Class object. 
class Subject
  belongs_to :grade  
end

class Student < ActiveRecord::Base
  has_many :enrollments
  has_many :schools, through: :enrollments
end

State.find(1).students 将通过 SchoolEnrollment 加入。

展平结构需要 states_students 联接 table,由于数据重复,这非常不合时宜。重复意味着在创建/更新学生时更慢的插入和更新查询。这同样适用于科目和成绩。

这没有解决当前和以前学生之间的区别,这可以通过添加结束日期或表示状态的枚举来解决Enrollment

处理可能由所有年级或 类 共享的数据已经够麻烦了。例如,将在州一级而不是学校一级设置的目标。另一种情况是一门可能延伸到几个年级的科目。