1

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

  • Variation 1 (total: 22)

    • Storage A: 12
    • Storage B: 10
  • Variation 2 (total: 234)

    • Storage A: 12
    • Storage B: 10
    • Storage C: 212

@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 %>

1 Answer 1

1

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 %>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.