Rails rails 有没有什么办法在创建一个表的信息的同时创建另一张关联表的多条信息?

ZhouYiYu · 2017年09月08日 · 最后由 eric_chao 回复于 2017年09月14日 · 1317 次阅读

比如我现在有一个教师表(teachers),关联的学生表 (students),
我想实现以下功能:
1,在我录入某个教师信息,比如 a 教师的同时,可以录入该教师所拥有的学生信息,比如 b,c,d,其中 b,c,d 为三个不同的学生。

关联加上 autosave,直接 teacher.students.new(xxx); teacher.save

看起来需要的是 nested-form 的功能:https://github.com/nathanvda/cocoon

不知道上面是不是你请要的答案 我猜测是不是不知道如何在 view,和 controller 怎么处理?

view:
依然是form_forpost 提交  update
只不过,teacherstudent,最好放两个table 里面,好辨认,参数列名请明朗
=text_field_tag "teacher_name"
=text_field_tag "student_a_name"
=text_field_tag "student_b_name"

controller:
params里面依然可以取到对应的参数,请分别处理,model请关联one_to_many
teacher = Teacher.new
teacher.name = params[:teacher.name]
..
student_a = Student.new
student_a.name = params[:student_a_name]
student_a.teacher_id = teacher .id
..
student_b = Student.new
student_b= params[:student_b_name]
student_b.teacher_id = teacher .id
..
respond_to do |format|
  if teacher.save
    student_a.save if teacher.save
    student_b.save if teacher.save
    format.html {   
     xxxxx  
     xxxxx 
    }
  else
    flash.now[:error]="xxxxxx"
    format.html { render :action => "xxx" }
    format.xml  { render :xml => @xxx.errors, :status => :unprocessable_entity }
  end
end
ZhouYiYu 关闭了讨论。 10月30日 15:58
需要 登录 后方可回复, 如果你还没有账号请 注册新账号