2012-08-16 116 views
0

我知道我很近,但我卡住了。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 

回答

2

使用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 %>