Skip to Content
Course content

82: Active Record Associations

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Think about how you organize a professional kitchen. You have a Head Chef who manages a team of Sous Chefs. From the Head Chef's perspective, they are looking at a group of people they're responsible for. But from a Sous Chef's perspective, they have exactly one boss they report to. Now, consider the ingredients. A specific recipe uses many ingredients, and a single ingredient—like salt—is used in almost every recipe in the building. That's a completely different kind of relationship.

In Active Record, associations are just a way of telling Ruby how these database tables relate to one another so you don't have to write manual SQL joins every time you want to find out who a task belongs to. I've spent years writing these, and the secret is realizing that the "relationship" is actually just a fancy wrapper around a foreign key (an ID column) in your database.

Linking the One-to-Many Chain

The most common relationship is the one-to-many. Let's use a project management app as our example. A Project has many Tasks, and each Task belongs to one Project.

class Project < ApplicationRecord
  has_many :tasks
end

class Task < ApplicationRecord
  belongs_to :project
end

Here is the part that trips people up: the belongs_to side is the one that actually holds the data. In your database, the tasks table must have a project_id column. I like to remember it this way: whoever "belongs to" the other is the one carrying the ID badge of their owner. Once you've set this up, you stop thinking about IDs and start thinking about objects. Instead of searching for tasks where project_id == 5, you just call my_project.tasks.

The Singular Focus of has_one

Sometimes you have a one-to-one relationship. Maybe a User has exactly one AccountSettings record. It looks almost identical to has_many, but it returns a single object instead of a collection.

class User < ApplicationRecord
  has_one :account_setting
end

class AccountSetting < ApplicationRecord
  belongs_to :user
end

Just like before, the AccountSetting table is the one that holds the user_id. If you find yourself using has_one and belongs_to on both sides, stop. You're overcomplicating it. Only one side can "belong" (hold the foreign key).

Managing the Many-to-Many Web

This is where things get interesting. What if a User can be assigned to many Projects, and a Project can have many Users? You can't put a user_id on the projects table, because there are too many users. You can't put a project_id on the users table, because they're in too many projects.

We solve this with a "join model." Think of it as a sign-up sheet. The ProjectMembership model exists solely to link a user to a project.

class User < ApplicationRecord
  has_many :project_memberships
  has_many :projects, through: :project_memberships
end

class ProjectMembership < ApplicationRecord
  belongs_to :user
  belongs_to :project
end

class Project < ApplicationRecord
  has_many :project_memberships
  has_many :users, through: :project_memberships
end

The through: :project_memberships part is the magic. It tells Active Record: "If I ask for a user's projects, first go look at the project_memberships table, find all the entries for this user, and then go grab the projects associated with those entries." It's a two-step jump, but Ruby handles it in one method call. I highly recommend using has_many :through over has_and_belongs_to_many because the join model allows you to store extra data—like the date the user joined the project—right on the relationship itself.




📋 Practical Task

Building a Course Enrollment System

You need to implement the backend associations for a learning platform. Your goal is to set up the models so that a student can be enrolled in multiple courses, and a course can have multiple students.

Requirements:

  • Create a Course model that has many Enrollments and many Students through those enrollments.
  • Create a Student model that has many Enrollments and many Courses through those enrollments.
  • Create an Enrollment model that belongs to both a Student and a Course.
  • Ensure the Course model also has a one-to-one relationship with a CourseSyllabus model (where the syllabus belongs to the course).

Write the Ruby code for these four classes. Make sure your associations are placed in the correct models and that you've correctly identified which model "belongs to" the others.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.