Forum: Ruby on Rails How to sort results of group_by

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Patrick D. (Guest)
on 2008-12-06 01:51
(Received via mailing list)
@areas.group_by(&:responsibility).each do |responsibility, areas|
  <p><%=h responsibility.name %></p>
  <% 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
Ed (Guest)
on 2008-12-06 02:34
(Received via mailing list)
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.
Patrick D. (Guest)
on 2008-12-06 05:42
(Received via mailing list)
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
Steve R. (Guest)
on 2008-12-07 05:24
(Received via mailing list)
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...
This topic is locked and can not be replied to.