Reputation:
This code here groups a Users friends by highschool name.
<% @user.friends.group_by(&:highschool_name).map do |hsname, friends| %>
<% next if hsname.blank? %>
<div class="contentbox">
<div class="box-header">
<h3><%= hsname %></h3>
</div>
<ul class="friends-list">
<% friends.map do |friend| %>
<li><%= image_tag(friend.image) %>
<% end %>
</ul>
</div>
<% end %>
But it groups with out any order, I would like to order by highste value. Showing the highest group first and down. Any ideas?
Upvotes: 2
Views: 1766
Reputation: 10907
group_by
gives you a hash in return. You can sort on count of values before iterating:
groups = @user.friends.group_by(&:highschool_name)
sorted_groups = groups.sort_by{|key, values| values.count}.reverse
sorted_groups.each do |hsname, friends|
# do your thing here
end
Upvotes: 2
Reputation: 5437
Did you try?
@user.friends.group(:highschool_name).order("highschool_name DESC")
Upvotes: 0