我通过名为Classes的连接表连接了Student和Teachers表。 我的目标是通过首先检查教师是否已经存在而将教师添加到学生档案中,如果没有,则创建新的教师档案。这些课程目前并不重要。有人可以把我推向正确的方向,因为我只是一个初学者,我在指南中找不到解决方案。
class Student < ActiveRecord::Base
has_many :classes
has_many :teachers, through: :classes
end
class Class < ActiveRecord::Base
belongs_to :student
belongs_to :teacher
end
class Teacher < ActiveRecord::Base
has_many :classes
has_many :students, through: :classes
end
感谢帮助新手!
答案 0 :(得分:0)
你说'课程目前并不重要',但是你无法连接学生和学生没有班级的老师。
如果你与老师有直接关系,我会这样做;
1 -
@student.teachers << @teacher unless @student.teachers.include?(@teacher)
2 -
@student.teachers.find_or_create_by(params[:teacher])
3 -
#Rails 3
@teacher = @student.teachers.find_or_initialize_by_id(params[:teacher_id])
@teacher.save
4 -
student = @class.build_student
teacher = @class.build_teacher
student.teachers << teacher
student.save
teacher.save