如何在Rails中按计数分组并按顺序排序?

时间:2013-12-23 22:29:30

标签: sql ruby-on-rails ruby ruby-on-rails-4 rails-activerecord

如何将此SQL转换为Ruby / Rails?

select tag, count(*) c from tags group by tag order by c desc;

我发现我能做到:

Post.select(:user_id).group(:user_id).count
Post.count(group: :user_id)
Post.all(group: :user_id, select: "user_id, count(*) as count")
Post.find(:all, select: "user_id, count(*) as count", group: :user_id)

#1返回一个哈希值。 #2,#3和#4给出了弃用警告。 (我正在使用Post,因为我还没有Tag的任何数据。)

1 个答案:

答案 0 :(得分:2)

尝试:

 Tag.select("tag, count(*) as total_count").group("tag").reverse_order

有关详细信息,请参阅:http://guides.rubyonrails.org/active_record_querying.html