每个循环:显示项目一次和总和数量

时间:2013-10-17 14:53:19

标签: ruby-on-rails ruby loops unique

我目前正在使用此代码来循环特定日期的订购商品

<tr>
  <th>Item</th>
  <th>Quantity</th>
</tr>
<% @demand.each do |d| %>
  <% d.demand_items.each do |item| %>
    <tr>
      <td><%= item.item.name %></td> 
      <td><%= @item_count %></td>
    </tr>
  <% end %>
<% end %>

目前,如果第1项被订购多次,它会在列表中多次显示。我只想让它出现一次并在旁边有一个数字来显示订购了多少。例如,如果item_1的demand_1数量为5,而item_1的数量为10,则结果应为:

  

item_1 .... 15

谢谢!

2 个答案:

答案 0 :(得分:3)

这应该这样做:

<tr>
  <th>Item</th>
  <th>Quantity</th>
</tr>
<% @demand.flat_map(&:demand_items).group_by(&:item).each do |item, demands| %>
  <tr>
    <td><%= item.name %></td>
    <td><%= demands.map(&:quantity).inject(:+) %></td>
  </tr>
<% end %>

希望这有帮助!


一些解释:

@demand.flat_map(&:demand_items)
# equivalent: (long version)
@demand.map{ |demand| demand.demand_items }.flatten
# retrieves all demand_items of each demand in the @demand list
# flatten the result (which is a double-dimension array)

demands.map(&:quantity)
# sends .quantity call to each element of the demands list
# and put it in an array (so this returns an array of quantity of each demand)
# equivalent: (long version)
demands.map{ |demand| demand.quantity }

demands.map(&:quantity).inject(:+)
# the inject(:+) will inject the method + (add) between each element of the array
# since the array is a list of quantities
# the inject(:+) sums each quantity of the list

答案 1 :(得分:2)

我会尝试获取独特的项目,然后在循环时对它们进行计数,例如:

(@demand.demand_items.sort.uniq).each do |d|
  d.item_name
  d.demand_items.count
end

这是未经测试的伪代码。