我仍然在学习使用Rails创造性,并且可以使用以下Rails协会的最佳实践指南:
我有三个模特,教师,学生和&类。教师可以教授任意数量的课程,学生可以参加任意数量的课程,课程只由一名教师授课,但可以有1-5名学生。
我的第一个假设是使用以下内容:
类别: belongs_to老师 has_many学生
教师: has_many:学生通过=>类
生: has_many:老师通过=>类
我不知道这是否合适,我看到了加入表格的建议。任何指导将不胜感激 !
更新:根据以下有用用户的反馈,我建议采用以下解决方案。有人可以验证一下吗?因为学生可以有很多课程并且属于一个班级,反之亦然,我需要两个连接表
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
答案 0 :(得分:0)
班级不是一个好名字, ClassRoom 更好
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
通过关联(has_many,has_one,belongs_to)自动创建表连接。你可以访问教师的所有学生,如
teacher.classrooms.first.students e.g.
我希望这对你有所帮助。