【问题标题】:How can I associate students to the school through two levels (courses and course sections) in rails 3.1?如何通过 rails 3.1 中的两个级别(课程和课程部分)将学生与学校联系起来?
【发布时间】:2023-03-16 05:04:01
【问题描述】:

一所学校有很多课程。一门课程有很多部分。学生注册课程的一部分。我希望能够找到学校的所有学生。

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

enrollment 只是一个表格,其中包含学生在课程的该部分注册时的部分 ID 和学生 ID。

有没有更好的方法来做我想做的事情?

谢谢。

【问题讨论】:

    标签: ruby-on-rails rails-models rails-3.1


    【解决方案1】:

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

    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(&amp;:sections).flatten.map(&amp;:students).flatten。我相信您将能够进一步详细说明。

    【讨论】:

      猜你喜欢
      • 2018-07-03
      • 2019-11-30
      • 2019-02-11
      • 2021-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多