Rails 3 Select Distinct Order By Number of Occurrences
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.
精彩评论