Rails 4 - 根据关联模型对ActiveRecord项目进行分组

时间:2016-03-18 10:07:57

标签: ruby-on-rails ruby-on-rails-4 activerecord

我有一个Rails 4应用程序,我正在制作一张桌子,向我展示我库存的物品。没有库存的商品会显示 NOT

在我的控制器中,我执行以下操作:

@stock = Stock.all

在我看来,我有这个:

<table>
<% @stock.each do |item| %>
    <tr>
        <td><%= item.id %></td>
        <td><%= item.product.id %></td>
        <td><%= item.product.description %></td>
    </tr>
<% end %>
</table>

这是结果:

+---------------------------------------------+
| Stock ID | Product ID | Product description |
+---------------------------------------------+
| 1        | 63         | A cool wheel        |
+---------------------------------------------+
| 2        | 63         | A cool wheel        |
+---------------------------------------------+
| 3        | 63         | A cool wheel        |
+---------------------------------------------+
| 4        | 26         | A red coat          |
+---------------------------------------------+
| 5        | 26         | A red coat          |
+---------------------------------------------+
| 6        | 99         | Something           |
+---------------------------------------------+
| ...      | ...        | ...                 |

但我希望按金额分组。我怎么能做到这一点?

这就是我想要的

+---------------------------------------------+
| Amount   | Product ID | Product description |
+---------------------------------------------+
| 3        | 63         | A cool wheel        |
+---------------------------------------------+
| 2        | 26         | A red coat          |
+---------------------------------------------+
| 1        | 99         | Something           |
+---------------------------------------------+
| ...      | ...        | ...                 |

我认为这会做到,但它不起作用:

.count(:all, group: "product_id")

2 个答案:

答案 0 :(得分:0)

ActiveRecord具有group功能。

如何使用它,您可以在指南中找到它:http://guides.rubyonrails.org/active_record_querying.html#group

答案 1 :(得分:0)

嘿,你可以试试这种方式

@stock = Stock.joins(:product).select("count(product_id) as amount,products.id as product_id, products.description as product_description").group("product_id")