0

I have a teacher model which is inherited from user model and a separate class model. Now I need to set up many_to_many relationship between teacher model and class model.

How can i do this, I'm little confused?

user229044
  • 232,980
  • 40
  • 330
  • 338
Vishal Goel
  • 170
  • 1
  • 1
  • 10

1 Answers1

0

See http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

You need an intermediate table to map teachers to classes.

class Teacher < User
  has_many :teacher_classes
  has_many :classes, through: :teacher_classes
end

class TeacherClass < ApplicationRecord
  belongs_to :teacher
  belongs_to :class
end

class Class < ApplicationRecord
  has_many :teacher_classes
  has_many :teachers, through: :teacher_classes
end

You will need to change Class to a name that does not conflict with the builtin ruby Class.

Carson Crane
  • 1,197
  • 8
  • 15
  • And belongs_to should have foreign_key option defined, because of the STI. – DonPaulie Apr 06 '18 at 12:16
  • Do you really need to do that? The asker wants the relation to be to the child table not the parent table. – Carson Crane Apr 06 '18 at 12:18
  • I would suggest that you do _not_ try to do `class Class`, as `Class` is already a class that exists in ruby, and you probably don't want to override anything in it. – Frost Apr 06 '18 at 12:19
  • can i also use has_and_belongs_to_many here instead of through table? – Vishal Goel Apr 06 '18 at 12:21
  • You can probably do that, but it is often a better idea to do the `has_many :through` approach. Using `has_and_belongs_to_many` will also generate a join table, and I would say that it's fairly common that you will want some kind of additional metadata on that relationship. – Frost Apr 06 '18 at 12:26
  • Actually i have many models like Teacher,Student and Parent all models are inherited from User model.Teacher model has many_to_many relationship with Class model and Student, Parent model have has_one relationship with Class model. – Vishal Goel Apr 06 '18 at 12:44