rails group by来制作嵌套表

时间:2011-11-08 01:35:54

标签: ruby-on-rails-3 group-by

我有产品和库存。每个库存包含product_id, color_id, storage_id and in_stock

对于给定的产品,我想按存储分组,然后颜色和输出in_stock,如:

存储1

  • 存储1
    • 颜色A:in_stock
    • 颜色B:in_stock
  • 存储2:
    • 颜色A:in_stock
    • 颜色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>

1 个答案:

答案 0 :(得分:0)

按存储顺序,然后颜色。然后在结果上使用group_by函数,这将创建一个以Storage Id作为键的有序哈希。因为你是按照存储和订购方式订购的颜色,排序将保持在哈希。

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

现在在您的视图中,您可以遍历哈希。

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

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

请原谅erb语法,如果正确的话,我已经习惯了HAML标记。