2014-08-30 36 views
-2

我通过名为Classes的连接表连接了Students和Teachers表。 我的目标是通过首先检查教师是否已经存在,如果不存在,然后创建新的教师档案,将老师添加到学生档案中。这些课目前并不重要。有人可以把我推向正确的方向,因为我只是一个初学者,我无法在指南中找到解决方案。如何在特定情况下通过使用控制器添加has_many?

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

你说过'此刻不重要',但不能连接学生&没有课堂的老师。

如果你与老师有直接的关系,我会做;

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 
相关问题