Search code examples
ruby-on-railsrubyassociationsmodels

How to set up associations in Ruby on Rails?


I'm building a sample app for practice and am having trouble determining the best way to organize my models and associations. So let's just say I have 3 models:

  1. Schools
  2. Classes
  3. Students

I want:

  • schools to have many classes
  • classes to have many students
  • classes to belong to a school
  • students to be enrolled in many classes in many different schools

The associations are making me dizzy, I'm not sure which ones to use. Help would be greatly appreciated.


Solution

  • Renamed class to course, as the class name Class is already taken. A join class such as enrollments would handle your many to many course <=> student relationship.

    class School
      has_many :courses
    end
    
    class Course
      belongs_to :school
      has_many :enrollments
      has_many :students, :through => :enrollments
    end
    
    class Student
      has_many :enrollments
      has_many :courses, :through => :enrollments
    end
    
    class Enrollment
      belongs_to :course
      belongs_to :student
    end