2013-08-07 175 views
0

如何将员工的Attendance保存在Attendance表中。 协会:与关联模型的复选框值

  1. 员工的has_many:出勤。
  2. 出勤belongs_to:员工。

下面是代码:

<%= form_for @attendance do |f| %> 
<%= f.date_select :date %><br /> 
<button type="button" id="check_all"> 
    EmployeeName/Attendance 
</button><br /> 
<table> 
<%#= hidden_field_tag "attendance[is_present]", '0'%> 
<% Employee.all.each do |emp|%> 
<tr> 
    <td> 
    <%= emp.first_name %><%= emp.last_name %></td> 
    <td style="padding-left:50px;"> 
    <%#= check_box_tag 'attendance[is_present]', 1, (@data.attendance.is_present == 1 ? true : false)%> 
    <%= f.check_box :is_present %></td> 
    <td> 
     <%= attendance.inspect %> 
    <% @attendance.employee_id = emp.id %> 
    </td> 
</tr> 
<% end %> 
</table> 
<script type='text/javascript'> 
    $('#check_all').on("click", function(){ $('input[type="checkbox"]').click(); }); 
</script> 
<%= f.submit %> 

<% end %> 

回答

0

如果考勤belongs_to员工,那么出勤表将有一个EMPLOYEE_ID列和给定的考勤将只能链接到一个员工。所以我认为你可能想改变你的模型,这样你在Employee和Attendance之间有一个has_and_belongs_to_many关系。那么你需要一个attendances_employees表来加入它们。

在模型之间建立连接后,请检查Handle check box forms with an `:has_many :through` Record Association。在这个问题下有一个评论,指向http://millarian.com/programming/ruby-on-rails/quick-tip-has_many-through-checkboxes/,它有一个非常有用的例子。以防万一,该网站曾经消失了,这里是你想设置你的观点是什么:

<% Employee.all.each do |emp|%> 
    <tr> 
    <td> 
     <%= label_tag "employee_id_#{emp.id}", "#{emp.first_name} #{emp.last_name}" %> 
    </td> 
    <td style="padding-left:50px;"> 
     <%= check_box_tag :employee_ids, emp.id, @attendance.employees.include?(emp), name: "attendance[employee_ids][]", id: "employee_id_#{emp.id}" %> 
    </td> 
    </tr> 
<% end %> 

您还需要有attr_accessible :employee_ids在你的考勤模式。