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?
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]]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With