开发者

Rails 3 Select Distinct Order By Number of Occurrences

开发者 https://www.devze.com 2023-03-02 19:16 出处:网络
In one of my models I have a country column. How would I go about selecting the top 3 countries based on how many mo开发者_StackOverflow社区dels have that country?Without any further information you c

In one of my models I have a country column. How would I go about selecting the top 3 countries based on how many mo开发者_StackOverflow社区dels have that country?


Without any further information you can try this out:

YourModel.group('country').order('count_country DESC').limit(3).count('country')

when you call count on a field rails automatically adds an AS count_field_name field to your query.

Count must be called at the end of the query because it returns an ordered hash.

0

精彩评论

暂无评论...
验证码 换一张
取 消