【问题标题】:checkbox value with associated model具有关联模型的复选框值
【发布时间】:2013-08-08 09:55:16
【问题描述】:

如何将员工的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 %>

【问题讨论】:

    标签: ruby-on-rails ruby checkbox associations


    【解决方案1】:

    如果出勤belongs_to 员工,则出勤表将有一个employee_id 列,并且给定的出勤将只能链接到一名员工。因此,我认为您可能想要更改模型,以便在员工和出勤之间建立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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-29
      • 1970-01-01
      • 1970-01-01
      • 2014-06-16
      • 1970-01-01
      • 2013-01-22
      • 1970-01-01
      相关资源
      最近更新 更多