[Ruby] Railsでgroup_by

less than 1 minute read

Sort group IDs in descending order of members

group_id user_id
1 1
1 2
1 3
2 2
3 1
3 3

groupsHash = groups.group(:group_id).order('count(user_id) desc').count(:user_id)
#=> {1=>3, 3=>2, 2=>1}

Get an array of group IDs with more than two people from here


ids = groupsHash.filter_map{ |group| groupsHash[0].to_i if groupsHash[1] >= 2}

#=> [1, 3]