【发布时间】:2018-11-16 02:08:43
【问题描述】:
这是我在模型文件中的查询方法:
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
这是我得到的示例数据库查询结果:
[
{
"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
},
....
]
我希望在视图中使用的最终 JSON 结果应该是这样的:
[
{
"id":null,
"brand_id":43,
"quantity": [
{
"category_id": 1,
"count": 2
},
{
"category_id": 2,
"count": 5
},
{
"category_id": 3,
"count": 4
}
]
},
....
]
我怎样才能实现它?改变模型方法?在将结果发送到视图之前在控制器中重建结果?如何?
任何建议将不胜感激。谢谢你。
更新:
根据@cmrichards 的回答,我想出了这个私有方法,在控制器中调用,然后在视图中使用。我在这里包括我的工作,虽然这些代码不是那么干燥:
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
如果您愿意,请通过编辑我的问题将它们弄干。 ;)
【问题讨论】:
-
品牌和品类如何关联?
-
@Gabbar,他们没有。但是一个品牌可以有不同类别的产品,同样,一个类别可以包含不同品牌的产品。我不确定我写的预期 JSON 结果是否正确。我正在尝试在堆积条形图或分组条形图中显示这些统计信息。我可以分别获得每个品牌和每个类别的结果,但我想将它们组合在一起。
标签: ruby-on-rails arrays json hash