0

学校には多くのコースがあります。コースには多くのセクションがあります。学生がコースのセクションに登録します。学校の生徒全員を見つけられるようにしたいです。

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 を含む単なるテーブルです。

私がここでやろうとしていることを行うためのより良い方法はありますか?

ありがとう。

4

1 に答える 1

0

正解かどうかはわかりませんが、少し異なる関係を作成します。学校には多くのコースがあり、コースには多くのセクションがあり、セクションには登録を通じて多くの学生がいます。これにより、次のモデルが作成されます。

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。これについては、さらに詳しく説明していただけると思います。

于 2012-01-15T22:19:18.917 に答える