Reputation: 437
I have a LineItem model with columns team and quantity. I am trying to run a loop to get total quantity of team "x".
<table>
<thead>
<tr>
<th>Team</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<% for line_item in @order.line_items %>
<tr>
<td><%= line_item.team %></td>
<td><%= line_item.quantity %></td>
</tr>
<% end %>
</tbody>
</table>
Here is a pretty picture of the table. Basically, I want the sum of all the teams named "USC" instead of seeing a line for each of them. Any help would be appreciated.
Upvotes: 0
Views: 66
Reputation: 2791
<% line_items = @order.line_items.select('team, sum(quantity) as total_quantity').group('team') %>
<% line_items.each do |line_item| %>
<tr>
<td><%= line_item.team %></td>
<td><%= line_item.total_quantity %></td>
</tr>
<% end %>
Upvotes: 0
Reputation: 1663
In your controller:
@line_items = @order.line_items.group(:team).sum(:quantity)
In your view:
<% @line_items.each do |team, quantity| %>
<tr>
<td><%= team %></td>
<td><%= quantity %></td>
</tr>
<% end %>
Upvotes: 2