在Rails-5中按数组列值分组

时间:2019-06-24 07:28:31

标签: ruby-on-rails postgresql ruby-on-rails-5

我有一个有趣的问题

我想按表的数组列中的各个值进行计数

例如

用于用户模型

Map(cbind, lst1, new = names(lst1))

我想说

id |  community_ids
1  |  {2, 4}
2  |  {2, 5} 
3  |  {2, 4}

我有解决办法

Community| User count
  2      | 3
  4      | 2
  5      | 1

但是问题是我正在遍历所有用户

谢谢

1 个答案:

答案 0 :(得分:0)

SQL版本可能类似于:

SELECT unnest(community_ids) AS community_id, count(*) AS count
FROM users 
GROUP BY community_id;

将其映射到Rails AR也很安静,可以用不同的方式完成,我将以最简单的方式进行转储:

sql = "SELECT unnest(community_ids) AS community_id, count(*) AS count
FROM users 
GROUP BY community_id"
results = ActiveRecord::Base.connection.execute(sql).to_a
# results should look something like: [{"community_id"=>2,"count"=>3}...]

PS:这种方法来自here