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
Student: has_many :classes. Basically the relationship between Student and Class is HABTM. Everything else looks fine. - Nitish ParkarTeacher has_many :classrooms. For students, what you currently have is fine. - Nitish Parkar