DEV Community

Cover image for Database design
Aleksei Borovikov
Aleksei Borovikov

Posted on

1

Database design

In database design, handling many-to-many relationships typically requires a third table, often called a join table or a junction table. This table records the associations between the two other tables. In contrast, for one-to-many relationships, you do not need a third table. Instead, you usually add a foreign key column in the table that represents the “many” side of the relationship.

Many-to-Many Relationship Example

Suppose you have students and courses tables, where each student can enroll in many courses, and each course can have many students. To model this relationship, you would create a third table, often named enrollments. This join table would include foreign keys referencing the primary keys of the students and courses tables.

class Student < ActiveRecord::Base
  has_many :enrollments
  has_many :courses, through: :enrollments
end

class Course < ActiveRecord::Base
  has_many :enrollments
  has_many :students, through: :enrollments
end

class Enrollment < ActiveRecord::Base
  belongs_to :student
  belongs_to :course
end
Enter fullscreen mode Exit fullscreen mode

One-to-Many Relationship Example

Suppose you have authors and books tables, where each author can write many books, but each book is written by only one author. In this case, you would add a foreign key column to the books table to reference the authors table.

class Author < ActiveRecord::Base
  has_many :books
end

class Book < ActiveRecord::Base
  belongs_to :author
end
Enter fullscreen mode Exit fullscreen mode

In summary, a third table is necessary for many-to-many relationships but not for one-to-many relationships.

Heroku

Amplify your impact where it matters most — building exceptional apps.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

Image of PulumiUP 2025

From Cloud to Platforms: What Top Engineers Are Doing Differently

Hear insights from industry leaders about the current state and future of cloud and IaC, platform engineering, and security.

Save Your Spot

👋 Kindness is contagious

Dive into this informative piece, backed by our vibrant DEV Community

Whether you’re a novice or a pro, your perspective enriches our collective insight.

A simple “thank you” can lift someone’s spirits—share your gratitude in the comments!

On DEV, the power of shared knowledge paves a smoother path and tightens our community ties. Found value here? A quick thanks to the author makes a big impact.

Okay