以下每个类别将获得一个帖子:
Post.group(:category_id).order('count *')
然后我可以显示一张代表帖子的表格,通过列出每个结果每个类别一个:
CATEGORY | SAMPLE POST ID | SAMPLE POST TITLE
1 | 123 | How to swim out loud
2 | 246 | On Hamlet
但是,我想包括此类别中的帖子数,例如:
CATEGORY | AMOUNT | SAMPLE POST ID | SAMPLE POST TITLE
1 | 5 | 123 | How to swim out loud
2 | 2 | 246 | On Hamlet
我们怎样才能同时显示数量,即“每组计数”?希望有一种方法可以将其作为适当的 ActiveRecord 查询的一部分从“发布”结果中提取出来。
请注意,此处没有“类别”表。 category_id 只是一个独立的列。因此 counter_cache 是不可能的。
最佳答案
您可以使用一些 sql-magic(以下适用于 mysql,尚未在 postgres 中测试,但也应该如此):
posts = Post.group(:category_id).order('count(*)').select('count(*) as category_cnt, posts.*')
category_count = posts.first.category_cnt
关于mysql - Rails : List items by frequency, 包括频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54127616/