比如我现在有一个教师表(teachers),关联的学生表 (students), 我想实现以下功能: 1,在我录入某个教师信息,比如 a 教师的同时,可以录入该教师所拥有的学生信息,比如 b,c,d,其中 b,c,d 为三个不同的学生。
这个 http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html ?
关联加上 autosave,直接 teacher.students.new(xxx); teacher.save
看起来需要的是 nested-form 的功能:https://github.com/nathanvda/cocoon
不知道上面是不是你请要的答案 我猜测是不是不知道如何在 view,和 controller 怎么处理?
view: 依然是form_for,post 提交 update 只不过,teacher,student,最好放两个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