如何对与 HAS-MANY 关系轨道关联的多对多关系进行建模



我有以下情况:

学生belongs_to并拥有许多课程,
课程has_many课程
belongs_to课程

这是我目前的模型:

class Student < ActiveRecord::Base
has_many  :studentcourses
has_many  :courses, :through => :studentcourses
end
class StudentCourse < ActiveRecord::Base //join table
belongs_to :course
belongs_to :student
end

class Course < ActiveRecord::Base
has_many  :studentcourses
has_many  :students, :through => :studentcourses
has_many  :lessons
end
class Lesson < ActiveRecord::Base
belongs_to :course
end

因此,学生被分配到 1 门或多门课程,而课程有很多课程。 如何对其进行建模,以便检索学生的所有课程的所有课程以及属于课程的所有学生?

使用本机has_and_belongs_to_many关系并指定比Student具有许多LessonsCourses

class Student < ActiveRecord::Base
has_and_belongs_to_many :courses
has_many :lessons, through: :courses
end
class Course < ActiveRecord::Base
has_and_belongs_to_many :students
has_many :lessons
end
class Lesson < ActiveRecord::Base
belongs_to :course
end

这是 HABTM 关系的迁移:

class CreateStudentsCourses < ActiveRecord::Migration
create_table :students_courses, id: false do |t|
t.belongs_to :student, index: true
t.belongs_to :course, index: true
end
end

通过这种方式,您可以@some_student.lessons所有学生的课程,但不幸的是,您无法获得@some_lesson.students,因为没有belongs_to :through关联,但您可以委派students方法:

class Lesson < ActiveRecord::Base
belongs_to :course
delegate :students, to: :course
end

这样,调用@lesson.students,方法students将在已定义此方法的关联Course上调用。

最新更新