aborov

Aleksei Borovikov

Posted on May 31, 2024

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.

💖 💪 🙅 🚩
aborov
Aleksei Borovikov

Posted on May 31, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Database design
beginners Database design

May 31, 2024