此查询
Message.where("message_type = ?", "incoming").group("sender_number").count
会给我一个哈希值。
OrderedHash {"1234"=>21, "2345"=>11, "3456"=>63, "4568"=>100}
现在我想按每组的数量排序。如何在查询中执行此操作。
答案 0 :(得分:101)
最简单的方法是在原始查询中添加一个order子句。如果为count方法指定一个特定字段,它将生成一个名为count_ {column}的输出列,该列可以在通过添加订单调用生成的sql中使用:
Message.where('message_type = ?','incoming')
.group('sender_number')
.order('count_id asc').count('id')
答案 1 :(得分:14)
当我尝试这个时,rails给了我这个错误
SQLite3::SQLException: no such column: count_id: SELECT COUNT(*) AS count_all, state AS state FROM "ideas" GROUP BY state ORDER BY count_id desc LIMIT 3
请注意,它表示SELECT ... AS count_all
所以我从@ Simon的答案中更新了查询,看起来像这样,它对我有用
.order('count_all desc')