Rails 3. Getting a Participation Form: How to Create Multiple Entries?
I know I'm around, but I'm stuck.
These are the three models I work with: attendance, attendance, and child.
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
So the unification model is attendance. I am trying to create an attendance sheet listing all students from a specific course and then use a checkbox to mark if they attended or not. Like this...
Attendance Sheet
Course: Biology
Date: _____________
Michael Scott [] Notes: sick
Jim Halpert [] Notes: ____
Dwight Schrute [] Notes: ____
Thus, the attendance tables have the following columns:
child_id
attended (boolean) to check if the student attended course or not
notes
In the part I'm having trouble with, some kind of loop appears to display all the students that belong to that class and the view and note fields for each one.
This is what I have ...
_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
source to share
Using rails accepts_nested_attributes_for :attendances
, you can do something like this in your controller:
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
Then do something like this in simple_form_for @attendance_sheet
<%= f.fields_for :attendances do |att| %>
<%= att.check_box :child, :label => att.object.child.full_name %>
<% end %>
source to share