DhatchXIX
DhatchXIX

Reputation: 437

rails sum of unique records in loop

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. enter image description here

Upvotes: 0

Views: 66

Answers (2)

Ilya Konyukhov
Ilya Konyukhov

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

Vincent Rolea
Vincent Rolea

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

Related Questions