2
votes

I'm still learning to get creative with Rails and could use some guidance on best practice for the following Rails association:

I have three models, Teachers, Students, & Classes. Teachers can teach any numbers of classes, students can join any number of classes, and a class is only taught by one teacher but can have 1-5 students.

My first assumption is to use the follwing:

Class: belongs_to teacher has_many Students

Teachers: has_many: students through => classes

Students: has_many: teachers through => classes

I don't know if this is appropriate and I've seen suggestions for joining tables. Any guidance would be appreciated !

Update: Given the feedback from the helpful users below, I'm suggesting the following solution. Can someone please verify this? Because a student can have many classes and belong to a class, and visa versa, I need two join tables

class ClassRoomEnrollment < ActiveRecord::Base
 belongs_to :students
 belongs_to :classrooms
end

class ClassRoom < ActiveRecord::Base
 belongs_to :teacher
 has_many :students through: classroomenrollment 

end

class Teacher < ActiveRecord::Base
 has_many :students :through => :classrooms
end

class Student < ActiveRecord::Base
 has_many :teachers :through => :classrooms
 has_many :classrooms through: classroomenrollment 
end
1
You missed Student: has_many :classes. Basically the relationship between Student and Class is HABTM. Everything else looks fine. - Nitish Parkar
Thanks @Nitish. Would I have to add Teacher has_many :classes as well ? - DaynaJuliana
And for the students, is has_many: classes replacing the has_many teachers through :classes relationship I added ? - DaynaJuliana
Yes, you will also need Teacher has_many :classrooms. For students, what you currently have is fine. - Nitish Parkar

1 Answers

0
votes

Class is not a good name, ClassRoom is better

class ClassRoom < ActiveRecord::Base
  belongs_to :teacher
  belongs_to :student # if I have well understand, this is the right association

  #some validations rules
  validates :<fieldname>, :<rule> => <value>, ...

  #callback like :before_save or :after_save, ....
end

class Teacher < ActiveRecord::Base
  has_many :students :through => :classrooms, :depend => :destroy

  #some validations rules
  validates :<fieldname>, :<rule> => <value>, ...

  #callback like :before_save or :after_save, ....
end

class Student < ActiveRecord::Base
  has_many :teachers :through => :classrooms, :depend => :destroy

  #some validations rules
  validates :<fieldname>, :<rule> => <value>, ...

  #callback like :before_save or :after_save, ....
end

With associations (has_many, has_one, belongs_to) joins through tables are automatically created. You can access all students of a teacher like

teacher.classrooms.first.students e.g.

I hope this help you.