A blog about software by Alexander Yaäkov Garber.

ActiveRecord Associations

This is a simple explanation of some basic concepts of Active Record Assocations.

School Example

We have the following entities:

  1. Classroom
  2. Teacher
  3. Pupil
  4. Subject

Active Record Assocations


Classroom has_one :teacher
Teacher belongs_to :classroom

Teacher has_many :courses
Course belongs_to :teachers

Course has_and_belongs_to_many :pupils
Pupil has_and_belongs_to_many :courses

Database Tables

classrooms
id
room_number
teachers foreign_key
id  
name  
classroom_id classrooms.id
courses foreign_key
id  
title  
teacher_id teachers.id
pupils
id
name
course_pupils foreign_key
pupil_id pupils.id
course_id courses.id