如何制作“数据透视表"在 Ruby on Rails 上? [英] How to make a "pivot table" on Ruby on Rails?
问题描述
首先,我想说我对 Ruby 和 Rails 完全陌生,我刚刚开始学习,所以如果我的问题看起来有点不清楚或过于宽泛,我深表歉意.
First, I'd like to mention I'm COMPLETELY new to Ruby and Rails, I'm on my very first days of learning, so I apologize if I seem a bit unclear or too broad with my questions.
我正在尝试做一些简单的事情(我认为?),即旋转表格.
I'm trying to do something simple (I think?), which is to pivot a table.
我有一张看起来像这样的表格:
I have a table that looks like this:
----------------------------------
| Name | Product ID | Amount |
|----------|----------------------
| Robert | P1 | 2 |
| Michael | P2 | 1 |
| Leonard | P2 | 1 |
| Robert | P2 | 4 |
| Robert | P3 | 2 |
| Michael | P3 | 1 |
----------------------------------
...我想把它变成这样:
... and I'd like to to turn it into something like this:
---------------------------
| Name | P1 | P2 | P3 |
---------------------------
| Robert | 2 | 4 | 2 |
| Michael | - | 1 | 1 |
| Leonard | - | 1 | - |
---------------------------
我不太确定如何实现这一目标.我环顾四周,没有发现任何针对我的问题的内容.
I'm not too sure how to achieve that. I've looked around and haven't found anything specific to my question.
我找到了一个名为 pivot_table 的 gem,可以在这里找到:https://github.com/edjames/pivot_table 但我不知道如何确切地使用它.里面有一个小指南,但我不知道把代码放在哪里.
I found a gem called pivot_table, which can be found here: https://github.com/edjames/pivot_table but I have no clue how to exactly use it. It has a small guide in it, but I don't know where to place the code.
非常感谢任何帮助.
谢谢.
推荐答案
看着你的表和你正在寻找的结果,我会这样做(我假设它是一个订单表?)
Looking at your table and the results you're looking for, I would do it like this ( I assume it's an orders table ?)
result = []
Order.all.group_by(&:name).each do |name, orders|
record = {}
record["name"] = name
orders.each do |order|
record[order.product_id] = order.amount
end
result.append(record)
end
我希望这会给你一个好的起点!
I hope this will give you a good starting point !
这篇关于如何制作“数据透视表"在 Ruby on Rails 上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!