My problem is two folded. First, I have a table that's not normalized that contains 3 pairs of data (6 columns), which have to be summed. It goes something roughly like this:
|-module_a-|-value_a-|-module_b-|-value_b-|-module_c-|-value_c-|
----------------------------------------------------------------
| 02 | 15 | nil | nil | nil | nil |
| 01 | 10 | 00 | 10 | nil | nil |
| 00 | 25 | nil | nil | nil | nil |
| 02 | 22 | 01 | 15 | 03 | 20 |
| 03 | 10 | nil | nil | nil | nil |
| 02 | 8 | 00 | 5 | nil | nil |
My main goal is to get a total sum of each module, but since they can be mixed in 3 fields, it becomes complicated to do it through activerecord (or so I think).
Anyway, to clean that up, I make an array like this:
tok1=Office.select('module_a as module, value_a as value')
tok2=Office.select('module_b as module, value_b as value').where.not(:value_b => nil)
tok3=Office.select('module_c as module, value_c as value').where.not(:value_c => nil)
tok=(tok1+tok2+tok3)
Result:
|-module-|-value-|
------------------
| 02 | 15 |
| 01 | 10 |
| 00 | 25 |
| 02 | 22 |
| 03 | 10 |
| 02 | 8 |
| 00 | 10 |
| 01 | 15 |
| 03 | 20 |
| 00 | 5 |
So far, so good.
Now, I'd like to make a sum of the module values. This would be very simple if I could do a GROUP and SUM via ActiveRecord, but the resulting variable tok
is an array, so no ActiveRecord functions are possible. If I try to merge them through tok=tok1.merge(tok2)
I end up with the results of tok2 only, which I assume is cause I'm renaming the fields when I query the Office table, I'm not sure. I tried putting them together in different ways, but I get an error that the relations are not immutable.
Anyway, since the result of doing tok=tok1+tok2+tok3
ends up with array, I'd like to do the sum by treating it as an array. I've tried using map
, and after doing a tok.map{|h| [h.module, h.value]}
I end up with an array like this:
{[02, 15], [01, 10], [00, 25}, [02, 22], [03,10], [02, 8], [00,10], [01,15], [03,20], [00, 5]}
I don't know how to proceed from here. I tried turning it into a hash, but I'm still too new to the map method so I don't know how to do that exactly. Ideally, I think, it should look like this:
{ ["02" => 15],["01" => 10],["00" => 25],["02" => 22],["03" => 10],["02" => 8],
["00" => 10],["01" => 15],["03" => 20],["00" => 5]}
I've read in other questions how to sum the values with a hash/array like that, so if I were to get it like this I think I'd be set.
Sorry for the messy explanation.