Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group collection by columns with rails

My table named stocks contains product_id, color_id, storage_id and in_stock as columns.

For a given product I want to group all stocks by storage, then for each storage I want to show product (color): in_stock

How should I write a method and how to render?

like image 867
Gaelle Avatar asked Nov 08 '11 05:11

Gaelle


2 Answers

<% Stock.all.group_by(&:storage).each do |storage, products| %>
  Storage: <%= storage %>
  <% products.each do |product| %>
    (<%= product.color_id %>): <%= product.in_stock %>
  <% end %>
<% end %>

Edit: updated to use ERB, and in_stock as a number and not a boolean yes/no column, and use color_id in place of color.name because that assumes you have a relationship to a color.

like image 147
Unixmonkey Avatar answered Sep 18 '22 17:09

Unixmonkey


Not structured exactly how you need it (not enough info from your post), but something like this perhaps?

items = Stock.select('color_id, in_stock').group('stocks.storage_id').where(:product_id => foo)

items.each {|item| puts "(#{lookup_color(item.color_id)}): #{in_stock}"
like image 38
lurker Avatar answered Sep 22 '22 17:09

lurker