English 中文(简体)
铁路集团,通过铺设板
原标题:rails group by to make nested table

我有产品和库存。 每个储量包含<条码>产品_id、彩色_id、储存_id和_stock。

对于特定产品,我想按储存方式将存货按肤色和产出分类,如:

储存

  • 储存
    • Color A: in_stock
    • Color B: in_stock
  • Storage 2:
    • Color A: in_stock
    • Color B: in_stock

不幸的是,我不能提出看法。

迄今为止,我提出以下问题:

def all_units_in_stock
  stocks.in_stock.group(:storage_id, :color_id).includes(:storage, :color)
end

which returns
Product.find(11).all_units_in_stock
Product Load (37.1ms)  SELECT "products".* FROM "products" WHERE "products"."id" = ? LIMIT 1  [["id", 11]]
Stock Load (0.3ms)  SELECT "stocks".* FROM "stocks" WHERE "stocks"."product_id" = 11 AND (in_stock > 0) GROUP BY storage_id
Storage Load (0.2ms)  SELECT "storages".* FROM "storages" WHERE "storages"."id" IN (1, 2, 3, 4, 5)
Color Load (0.2ms)  SELECT "colors".* FROM "colors" WHERE "colors"."id" IN (3)
=> [#<Stock id: 162, product_id: 11, storage_id: 1, in_stock: 10.0, created_at: "2011-11-07 22:54:50", updated_at: "2011-11-07 22:54:50", color_id: 3>, #<Stock id: 163, product_id: 11, storage_id: 2, in_stock: 10.0, created_at: "2011-11-07 22:54:50", updated_at: "2011-11-07 22:54:50", color_id: 3>
问题回答

Order by storage, then color. Then use the group_by function on the results, this will create an ordered hash with the Storage Id as the key. Because you ordered by storage & color, the ordering will be maintained in the hash.

products = Product.find(11).all_units_in_stock
@group_by_storage = products.group_by {|p| p.storage_id }

现在,你可以 through。

<% @group_by_storage.each do |key, value| %>
  <ul>
    <li><%= key %>

      <ul>
        <li><%= value.color_id %>
      </ul>
    </li>
  <ul>

如果是正确的话,请将Im用于HAML标志。





相关问题
Linq - 2 tables - Sum

Asiento ******** Id_Asiento integer key Fecha date It_Asiento ********** Id_Asiento integer Forenkey Importe float I wan to do This SQL Query with Linq select Asiento.Id_Asiento, ...

How to group by and order correctly

I have a problem ordering my results correctly when using the group by. It seems to show the first entry in the database instead of the most recent in the group. Example: id(autoincrement) | name ...

Need some help with SQL GroupBY

I have a two column table as follows: ID Emp ID 1 1 1 2 1 3 1 4 2 2 2 6 2 10 3 1 3 5 4 8 5 2 5 6 I need something like this: ID Emp ...

SQL Distinct Grouping?

Here is my query: SELECT dbo.EmailCampaignTracking.emailOpened, dbo.EmailCampaignTracking.emailUnsubscribed, dbo.EmailCampaignTracking.emailBounced, COUNT(*) FROM dbo.EmailCampaignTracking ...

Grouping with SubSonic 3

I have the following table "GroupPriority": Id Group Priority 1 1 0 2 2 0 3 3 0 4 2 1 5 1 1 6 2 2 7 ...

Group by named column

I always forget how to do things like this. I have a database table with birthdates and I want to find out how many people have the same age. I m trying: SELECT TIMESTAMPDIFF( YEAR, birthdate, ...

热门标签