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.
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.
Any help is greatly appreciated.
Thank you.
First install the gem
Then in your terminal, run
Say the model represented by your first table is
Sale
.Then you can use the other methods listed in the docs. For example
Note: this is just from reading the GitHub page you linked. I've never used the gem.
Edit:
You can put the code in a module:
Then you'd call it from somewhere else with
This way you can reuse the grid-generating code and call it with arbitrary parameters.
Looking at your table and the results you're looking for, I would do it like this ( I assume it's an orders table ?)
I hope this will give you a good starting point !
This is a general solution, that I implemented in
application_helper.rb
The first three parameters are capital-letter
ActiveRecord
subclass names, and thepivot_attribute
(which is an attribute ofpivot_model
) can be given as a symbol or a string. This assumespivot_model
is a many-to-many relation that referencesrow_model
andcolumn_model
as foreign keys. If there isn't a many-many model, I'm guessing some models could be repeated among the parameters, but I haven't kitchen tested it for that.The return value is an array of arrays.