Gaelle
Gaelle

Reputation: 599

Ruby on rails count and group with PostgreSQL

I need to fetch and group one model on various columns. My Stock model contains variation_id, color_id, storage_id, in_stock. Must work with SQLite and Postgre

I want to group by variation then by storage and display sum of in_stock

@stocks = Stock.locked.all

What th view should look like? So far I've been able to group by variation but don't know how to iterate over storage and do the calculation. How to extract the logic to move it to the model?

<% @stocks.group_by(&:variation).each do |variation, stocks| %>
   <h2><%= variation.name %> (<%= variation.color.name %>)</h2>
<% end %>

* EDIT *

Reworked the view. I get variation and storages in place but sum function fails undefined method '+' for #<Stock:0x007ff15a06cf68>

<% @stocks.group_by(&:variation).each do |variation, stocks| %>
  <h2><%= variation.name %> </h2>

  <% stocks.group_by(&:storage).each do |storage, stock| %>
    <li><%= storage.name %>: <%= stock.sum(:in_stock) %></li>
  <% end %>   
<% end %>

Upvotes: 1

Views: 219

Answers (1)

Gaelle
Gaelle

Reputation: 599

Data is correctly fetched. The error came from wrong way to manipulate the array returned. Here is the working code.

<% @stocks.group_by(&:variation).each do |v, stocks| %>
  <h3 class="variations"><%= v.name %>: <%= stocks.map {|x| x.in_stock}.sum %></h3>
  <% stocks.group_by(&:storage).each do |storage, s| %>
    <li><%= storage.name %>: <%= s.map {|x| x.in_stock}.sum %></li>
  <% end %>
<% end %>

Upvotes: 1

Related Questions