如何使用rails中的多个关联将轮班分配给员工?

时间:2015-06-08 11:48:43

标签: ruby-on-rails checkbox has-many mass-assignment

我有以下型号:

  1. 员工
  2. 它们之间的关系如下:

    • 转移has_many员工。
    • 员工belongs_to转移

    我希望有一个链接指向一个页面,该页面包含所有班次作为下拉列表,并且我希望所有员工都有复选框。

    我想从班次下拉列表中选择一个班次,我想通过使用复选框选择属于该班次的所有员工,以便将班次分配给所选员工。

    如何在Rails中实现这一点?

1 个答案:

答案 0 :(得分:0)

我认为你的架构是正确的。随着时间的推移,用户将与许多班次相关联,您可能需要提前计划,例如,您可以将单个用户分配给许多不同的屎,每天一个或一些。出于这个原因,轮班 - 员工关系需要多对多。我会喜欢这个

Shift
  has_many :employee_shifts
  has_many :employees, :through => :employee_shifts

Employee
  has_many :employee_shifts
  has_many :shifts, :through => :employee_shifts

EmployeeShift
  belongs_to :employee
  belongs_to :shift

然后,当您分配轮班时,您可以通过操纵每个员工的shift_ids getter / setter,操纵employee_ids getter / setter来执行此操作每个班次。

您谈到的要求有点复杂,因为这意味着当更改换档选择时,您需要更改显示的复选框列表,例如使用ajax,因为您需要检查或根据员工是否已分配到该班次,取消选中此框。我认为将它作为一个表格会更好,例如,显示下周的所有轮班或其他内容。例如

这会创建一个表格,其中包含班次列和每位员工的行 该表格的形式将通过像params[:shifts] = {1 => {:employee_ids => [5,8,10]}, 2 => {:employee_ids => [6,7,8]}}

这样的散列发送
 <table>
   <thead>
     <tr>
       <th>Employee</th>
       <% @shifts.each do |shift| %>
         <!-- this is the column header for a single shift. display the appropriate data, i'm guessing here -->
         <th><%= shift.time %></th>
       <% end %>
     </tr>
   </thead>
   <tbody>
     <% @employees.each do |employee| %>
       <tr>
         <!-- some employee specific data in the first column -->
         <td><%= employee.name %></td>
         <% @shifts.each do |shift| %>
           <td><%= checkbox_tag "shifts[#{shift.id}][employee_ids][]", employee.id, shift.employee_ids.include?(employee.id) %></td>
         <% end %>
       </tr>
     <% end %>
   </tbody>
 </table>

然后,在此表单提交的控制器中,您可以执行以下操作:

 params[:shifts].each do |id, attributes|
   if shift = Shift.find_by_id(id)
     shift.employee_ids = attributes[:employee_ids] || []
     shift.save
   end
 end