Rails both way relationship between two tables

89 Views Asked by At

In Ruby on Rails I'm trying to be able to create both way many-to-many relationship between two tables. I want a relationship in routes and controllers. For example I want to be able to do both of the things below:

teachers = school_class.teachers.all school_classes = teacher.school_classes.all So if you could help me with the routing setup, controllers and the model for this problem I would appreciate it.

I tried using a has_and_belongs_to_many association and I think that is the right way to go but I couldn't figure out anything else.

1

There are 1 best solutions below

0
tonystrawberry On

When you have a many-to-many relationship between two tables, you necessarily need a relationship table between them.

relationship_table

So first create a model that will create your relationship table.

rails g model TeacherSchoolClass teacher:reference school_class:reference

Then in your models/teacher_school_class.rb, add the belongs_to lines.

class TeacherSchoolClass < ApplicationRecord
  belongs_to :teacher
  belongs_to :school_class
end

Finally in both models/teacher.rb and models/school_class.rb, add the has_many/through lines.

class Teacher < ApplicationRecord
  has_many :teacher_school_classes, dependent: :destroy # Will destroy the related teacher_school_classes when teacher is destroyed
  has_many :school_classes, through: :teacher_school_classes # Will get all the school_classes for this teacher through the teacher_school_classes table
end

class SchoolClass < ApplicationRecord
  has_many :teacher_school_classes, dependent: :destroy # Will destroy the related teacher_school_classes when school_class is destroyed
  has_many :teachers, through: :teacher_school_classes # Will get all the teachers for this school_class through the teacher_school_classes table
end

You will then be able to get:

  • all the school classes for a specific teacher
  • all the teachers for a specific school class
teacher.school_classes # Returns an ActiveRecord::Relation of SchoolClass
school_class.teachers # Returns an ActiveRecord::Relation of Teacher

Reference: https://guides.rubyonrails.org/association_basics.html#the-has-many-through-association