我想创建一个活动记录查询并将结果存储在一个散列中,该散列包含来自关联表的摘要信息,如下所示。
以下是表格和关联:
Post belongs_to: category
Category has_many: posts
在这里,我想计算每个类别中的帖子数量,并创建一个摘要表,如下所示(使用所需表的SQL查询):
select c.name, count(p.id) from posts a left join categories c on p.category_id = c.id where p.status = 'Approved' group by (c.name) order by (c.name);
Category | count
---------------+-------
Basketball | 2
Football | 3
Hockey | 4
(3 rows)
最后,我想将结果存储在哈希中,如下所示:
summary_hash = { 'Basketball' => 2, 'Football' => 3, 'Hockey' => 4 }
如果您能指导我如何编写活动记录查询并将结果存储在哈希中,我将不胜感激。