“sorting”由“组”结果“数”

这个查询

Message.where("message_type = ?", "incoming").group("sender_number").count 

将返回给我一个哈希。

 OrderedHash {"1234"=>21, "2345"=>11, "3456"=>63, "4568"=>100} 

现在我想按每个组的数量来sorting。 我怎么能在查询内做到这一点。

最简单的方法是只在原始查询中添加一个订单子句。 如果您给count方法一个特定的字段,它将生成一个名为count_ {column}的输出列,可以在通过添加一个订单调用生成的sql中使用:

 Message.where('message_type = ?','incoming') .group('sender_number') .order('count_id asc').count('id') 

当我尝试这个,铁轨给了我这个错误

 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

所以我更新@西蒙的答案查询看起来像这样,它适用于我

 .order('count_all desc')