Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Active Record order by group size

I've got an active record query where I'm using group_by

@foo = Foo.group_by(&:relation)

Then in the view i'm using

@foo.each do |group, values|
 group x has values.count elements
end

Is there a way I could sort these by the count of each group?

like image 848
Beau Trepp Avatar asked Aug 08 '12 04:08

Beau Trepp


1 Answers

group_by is not a ActiveRecord method, group is. group_by is a Enumerator method.

What about

@foo = Foo.group('relation').order('count_id asc').count('id')

Taken from "Order by" result of "group by" count?.

Otherwise, if you want to sort it on Ruby level, you could do

disordered_hash = {:two=>[1, 2], :one=>[1], :three=>[1, 2, 3]}
ordered_array = disordered_hash.sort {|k, v| k[1].count <=> v[1].count} # add .reverse if you want
# => [[:one, [1]], [:two, [1, 2]], [:three, [1, 2, 3]]]
like image 55
oldergod Avatar answered Nov 12 '22 11:11

oldergod