这应该这样做:
<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