Rails 3.考勤表:如何创建多个记录?

我知道我很亲密,但我被困住了。

这些是我正在使用的三个模型:出勤表,出勤和儿童。

AttendanceSheet has_many :attendances, :dependent => :destroy accepts_nested_attributes_for :attendances belongs_to :course Child has_many :attendances Attendance belongs_to :attendance_sheet belongs_to :child 

所以连接模型是出勤。 我正在尝试创建一个考勤表,其中列出了来自特定课程的所有学生,然后使用复选框标记他们是否参加。 像这样…

 Attendance Sheet Course: Biology Date: _____________ Michael Scott [] Notes: sick Jim Halpert [] Notes: ____ Dwight Schrute [] Notes: ____ 

因此,考勤表有以下几列:

 child_id attended (boolean) to check if the student attended course or not notes 

我遇到麻烦的部分是提出某种循环来显示属于该类的所有学生,并为每个学生提供参加的笔记和笔记。

这就是我的……

_form.html.erb

  { :class => 'form-horizontal' } do |f| %> 

Course:

:string, :hint => 'YYYY-MM-DD', :input_html => {:class => :datepicker, :value => Date.today} %>
*** trouble here ***

attendance_sheets_controller.rb

 def new @attendance_sheet = AttendanceSheet.new @course = Course.find(params[:course_id]) respond_to do |format| format.html end end 

使用rails accepts_nested_attributes_for :attendances ,您可以在控制器中执行以下操作:

 def new @attendance_sheet = AttendanceSheet.new @course = Course.find(params[:course_id]) @course.children.each do |c| @attendance_sheet.attendances << Attendance.new(:child => c) end respond_to do |format| format.html end end 

然后在simple_form_for @attendance_sheet执行类似的simple_form_for @attendance_sheet

 <%= f.fields_for :attendances do |att| %> <%= att.check_box :child, :label => att.object.child.full_name %> <% end %>