我如何通过rails 3.1中的两个级别(课程和课程部分)将学生与学校联系起来



一所学校有很多课程。一门课程有很多部分。学生报名参加某一课程的某一部分。我想找到学校里所有的学生。

Class School < ActiveRecord::Base
  has_many :courses
  has_many :sections, :through => courses
  has_many :students, :through => courses, :through => sections, :through => enrollments
end
Class Course < ActiveRecord::Base
  belongs_to :school
  has_many :sections
  has_many :students, :through => sections, :through => enrollment
end
Class Section < ActiveRecord::Base
  belongs_to :course
  has_many :students, :through => enrollment
end
Class Student < ActiveRecord::Base
  has_many :sections, :through => enrollment
  has_many :courses, :through => sections, :through => enrollment
  has_many :schools, :through => courses, :through => sections, :through => enrollment
end

当一个学生注册该课程时,注册只是一个包含部分id和学生id的表。

有没有更好的方法来做我在这里要做的事情?

谢谢。

我不确定我是否答对了,但我会做一组稍微不同的关系:学校有很多课程,课程有很多板块,板块通过招生有很多学生。这将导致以下模型:

class School < ActiveRecord::Base
  has_many :courses
end
class Course < ActiveRecord::Base
  belongs_to :school
  has_many :sections
end
class Section < ActiveRecord::Base
  belongs_to :course
  has_many :enrollments
  has_many :students, :through => :enrollment
end
class Enrollment < ActiveRecord::Base
  belongs_to :section
  belongs_to :student
end
class Student < ActiveRecord::Base
  has_many :enrollments
  has_many :courses, :through => :enrollment
end

这将允许正确地引用各种数据。例如,我希望看到第一所学校所有课程的所有部分的所有学生。然后我会使用这样的东西:School.first.courses.map(&:sections).flatten.map(&:students).flatten。我相信你能够进一步阐述这一点。

最新更新