Rails 3.考勤表格:如何创建多个记录?
问题描述:
我知道我很近,但我卡住了。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
<%= simple_form_for @attendance_sheet, :html => { :class => 'form-horizontal' } do |f| %>
<h2>Course: <%= @course.name %></h2>
<div class="form-inputs">
<%= f.input :attendance_on, :as => :string, :hint => 'YYYY-MM-DD', :input_html => {:class => :datepicker, :value => Date.today} %>
</div>
<% @course.children.each do |child| %>
*** trouble here ***
<%= check_box_tag %> <%= child.full_name %><br />
<% end %>
<div class="form-actions">
<%= f.button :submit %>
</div>
<% end %>
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
<%= f.fields_for :attendances do |att| %>
<%= att.check_box :child, :label => att.object.child.full_name %>
<% end %>