简体   繁体   English

具有关联模型的复选框值

[英]checkbox value with associated model

How can I save Employee's Attendance in Attendance table. 我怎样才能节省员工AttendanceAttendance表。 Association : 协会:

  1. Employee has_many :Attendances. 员工has_many:出勤。
  2. Attendance belongs_to :Employee. 出勤属于_雇员:

Here is the code: 这是代码:

<%= 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 %>

If an Attendance belongs_to Employee, then the attendances table will have a single employee_id column and a given Attendance will only be able to link to one employee. 如果“出勤” belongs_to雇员”,那么“出勤”表将只有一个“ employee_id”列,并且给定的“出勤”将只能链接到一名雇员。 So I think you might want to change your model so that you have a has_and_belongs_to_many relationship between Employee and Attendance. 因此,我认为您可能希望更改模型,以便在员工与出勤之间建立has_and_belongs_to_many关系。 Then you'll need an attendances_employees table to join them. 然后,您将需要一个attendances_employees表来加入他们。

Once you have that connection between the models, check out Handle check box forms with an `:has_many :through` Record Association . 在模型之间建立连接后,请使用“:has_many:through”记录关联来签出“ 处理”复选框形式 There is a comment under the question that points to http://millarian.com/programming/ruby-on-rails/quick-tip-has_many-through-checkboxes/ which has a really helpful example. 在该问题下有一条评论指向http://millarian.com/programming/ruby-on-rails/quick-tip-has_many-through-checkboxes/ ,上面有一个非常有用的示例。 Just in case that site ever goes away, here is what you would want to set up in your view: 以防万一该站点消失了,这是您想要在视图中设置的:

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

You'll also need to have attr_accessible :employee_ids in your Attendance model. 您还需要在出勤模型中具有attr_accessible :employee_ids

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM