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.
When you have a
many-to-manyrelationship between two tables, you necessarily need a relationship table between them.So first create a model that will create your relationship table.
Then in your
models/teacher_school_class.rb, add thebelongs_tolines.Finally in both
models/teacher.rbandmodels/school_class.rb, add thehas_many/throughlines.You will then be able to get:
Reference: https://guides.rubyonrails.org/association_basics.html#the-has-many-through-association