Active recording order by group size

I have an active write request where I use group_by

@foo = Foo.group_by(&:relation) 

Then in the view I use

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

Is there a way to sort them by the number of each group?

+6
source share
1 answer

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

What about

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

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

Otherwise, if you want to sort it at the Ruby level, you can 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]]] 
+7
source

Source: https://habr.com/ru/post/922331/


All Articles