How to sort results of group_by


#1

@areas.group_by(&:responsibility).each do |responsibility, areas|

<%=h responsibility.name %>

<% areas.each do |area| %> ...

I see that #group_by iterates through my list of areas, splitting them
into
sets according to which ones have the same responsibility.

I would like to sort the results of that list.

It seems to me that group_by returns an OrderedHash. How to I sort
those
results prior to passing the |responsibility, areas| pairs?

–wpd


#2

The ordered hash is already sorted by responsibility, so you would
sort each area something like this: (tags removed)

@areas.group_by(&:responsibility).each do |responsibility, areas|
responsibility.name
areas.sort_by{|area| area.name}.each do |area|

A style suggestion: make yourself a method in class Area that returns
@areas_grouped_and_sorted. Less code in the view, and reusable.


#3

The problem is that the responsibilities are not already sorted going
in.
Each area belongs_to a responsibility. I have the list of all of the
areas,
I want to group them by responsibility, and I want to sort the result by
some field within the responsibility. Currently, I have something like:

@areas = Area.find(:all)

Is there some way to order that ahead of time by
areas.responsibility.some_field?

Hmmm… perhaps I’m thinking of this backwards. (It wouldn’t be the
first
time.) Do I really want to do something like:

@responsibilities = Responsibility.find(:all)

Hmmmm… that looks like the right avenue to have taken in the first
place…

now… if I could just figure out how to comment out blocks of ERB code,
this would be much easier to test and then back out of if it goes awry.

–wpd


#4

On Dec 5, 2008, at 7:40 PM, Patrick D. wrote:

now… if I could just figure out how to comment out blocks of ERB
code, this would be much easier to test and then back out of if it
goes awry.

<% if false -%>
commented out
<% end -%>

Works for me when I don’t have time to think up anything else…