Enrique Moreno Tent
Enrique Moreno Tent

Reputation: 25277

Rails 4 - Grouping and looping through a query while making a sum

So I have the following table Sales, with a polymorphic relationship:

----------------------------------
| id | product_id | product_type |
----------------------------------
|  1 |         45 | Rim::Entry   |
----------------------------------
|  2 |         45 | Rim::Entry   |
----------------------------------
|  3 |         23 | Tyre::Entry  |
----------------------------------
| .. |        ... |         ...  |

I would like to be able to loop through the Sales, and display them showing how many of each product was sold. This is my current partial:

<% @order.sales.???????.each do |sale| %>
    <p>Product ID: <%= sale.product_id %></p>
    <p>Product name: <%= sale.product.description %></p>
    <p>Amount sold: <%= sale.??? %></p>
<% end %>

And this is a sample of what I wish the output was:

Product ID: 45
Product Name: Rim Model AAA
Amount sold: 2

Product ID: 23
Product Name: TyreZ model XYZ
Amount sold: 1

...

Upvotes: 0

Views: 44

Answers (3)

Enrique Moreno Tent
Enrique Moreno Tent

Reputation: 25277

I found an answer, even though Im not sure it is the prettiest:

<% @order.sales.group(:product_id).count.each_pair do |product_id, count| %>
    <div class="product">
        <% product = @order.sales.where(product_id: product_id).first %>
        <p>Product_id: <%= product.product.description %></p>
        <p>Amount: <%= count %></p>
    </div>
<% end %>

Upvotes: 0

FixerRB
FixerRB

Reputation: 326

You can use group_by.

<% @order.sales.group_by { |s| s.product }.each do |product, sales| %>
    <p>Product ID: <%= product.id %></p>
    <p>Product name: <%= product.description %></p>
    <p>Amount sold: <%= sales.count %></p>
<% end %>

Upvotes: 1

Matt
Matt

Reputation: 14038

If you want the number sold for each product you should loop through the products, not the sales.

<% Product.includes(:sales).each do |product| %>
  <%= product.id %>
  <%= product.sales.count %>
<% end %>

Upvotes: 1

Related Questions