D.Hin
D.Hin

Reputation: 13

how to model a many-to-many relationship, associated with a has-many relationship rails

I have the following scenario:

Students belongs_to and has many courses,
courses has_many lessons
lessons belongs_to course

This is my current model:

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

Therefore students get assigned to 1 or many Courses, and Courses have many lessons. How can I model it so that I can retrieve all lessons of all the courses of a student and all the students that belong to lesson?

Upvotes: 0

Views: 121

Answers (1)

Vasili
Vasili

Reputation: 905

Use native has_and_belongs_to_many relationship and specify than Student has many Lessons through Courses:

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

And this is a migration for HABTM relationship:

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

This way you can get all student's lessons @some_student.lessons, but, unfortunately, you can't get @some_lesson.students, because there's no belongs_to :through association, but you can delegate students method:

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

This way, calling @lesson.students, method students will be called on an associated Course, which has this method defined.

Upvotes: 1

Related Questions