This is my query method in model file:
def self.sum_by_brand_category
result = Product.joins(:brand, :category)
.select("brands.id as brand_id, categories.id as category_id, sum(products.quantity) as count")
.group("brands.id, categories.id")
return result
end
Here is the sample database query result I get:
[
{
"id":null,
"brand_id":43,
"category_id":1,
"count":2
},
{
"id":null,
"brand_id":43,
"category_id":2,
"count":5
},
{
"id":null,
"brand_id":43,
"category_id":3,
"count":4
},
....
]
I would expect the final JSON result to be used in views should be like this:
[
{
"id":null,
"brand_id":43,
"quantity": [
{
"category_id": 1,
"count": 2
},
{
"category_id": 2,
"count": 5
},
{
"category_id": 3,
"count": 4
}
]
},
....
]
How can I achieve it? Change the model method? Rebuild the result in the controller before sending it to the view? and how?
Any suggestions will be appreciated. Thank you.
Updated:
Based on @cmrichards 's answer, I come up with this private method to be called in controller and then used in views. I am including my work here, although these are not so DRY codes:
private
def get_sum_by_brand_category
query_results = Product.sum_by_brand_category
results = []
query_results.group_by(&:brand_id).each do |brand_id, query_result|
result = {}
result[:id] = nil
result[:brand_id] = brand_id
quantity_array = []
query_result.each do |data|
quantity_block = {}
quantity_block[:category_id] = data.category_id
quantity_block[:count] = data.count
quantity_array.push(quantity_block)
end
result[:quantity] = quantity_array
results.push(result)
end
return results
end
Please DRYing them out if you'd like to, by editing my question. ;)