Rails active record query getting most common obje

2020-08-01 06:49发布

问题:

I am trying to query a model to get the most common field of a certain attributeso far I have

 Person.maximum('age')

But how do I query a group of lets say 6 of the most common ages. Any help would be much appreciated. thanks

回答1:

You will have to group persons by their ages and pick the group with the highest count. The code below will return both age and frequency of most frequent age.

Person.group('age').order('count_all').limit(1).count

To fetch the age only and not the count do

Person.group('age').order('count(*)').limit(1).pluck(:age).first