# Group by issue

**URL:** <https://www.ruby-forum.com/t/group-by-issue/92559>\
**Category:** Rails\
**Created:** [April 20, 2007, 6:29pm UTC](https://www.ruby-forum.com/t/group-by-issue/92559 "2007-04-20T18:29:31Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![dorelal](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/3da27b/32.png) [@dorelal](https://www.ruby-forum.com/u/dorelal)\
**Post date:** [April 20, 2007, 6:29pm UTC](https://www.ruby-forum.com/t/group-by-issue/92559/1 "2007-04-20T18:29:31Z")

</div>

I have a Person model and a Phone model.

A person can have any number of phones.

A phone has two attributes: type and number.

A phone type could be any of the followings:  
Home  
Work  
Mobile  
Fax  
Other

A person can have multiple records of home phones or any other phone  
type.

While displaying the phones this is what I am doing.

\<% @phones.group\_by(&:type).sort.each do |type, phones| %\>  
\<%= render :partial =\> 'phone, :collection =\> @phones %\>   
  
\<% end %\>

But the problem is that it is returning phone numebers in the following  
order:  
Fax  
Home  
Mobile  
Office  
Work

I want the phone numbers to be displayed in the following order:  
Work  
Mobile  
Home  
Fax  
Other

What’s the best way to achieve that?

---

<div class="post-metadata">

**Author:** ![dorelal](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/3da27b/32.png) [@dorelal](https://www.ruby-forum.com/u/dorelal)\
**Post date:** [April 20, 2007, 9:00pm UTC](https://www.ruby-forum.com/t/group-by-issue/92559/2 "2007-04-20T21:00:48Z")

</div>

On Apr 20, 2007, at 12:29 PM, Neeraj K. wrote:

> Fax  
> \<% end %\>  
> I want the phone numbers to be displayed in the following order:  
> Work  
> Mobile  
> Home  
> Fax  
> Other
> 
> What’s the best way to achieve that?

“Best”, Hmm, don’t know, but here’s what I’ve done for similar  
reasons (mapped into your domain):

class Phone  
SORT\_ORDER = %w[Work Mobile Home Fax Other]

def self.pos phone\_type=‘Other’  
SORT\_ORDER.index(phone\_type)  
end  
end

\<% @phones.group\_by(&:type).sort\_by {|k,v| Phone.pos(k) }.each do |  
type, phones| %\>  
\<%= render :partial =\> ‘phone’, :collection =\> phones %\>   
  
\<% end %\>

(I fixed what looked like two typos in the render line as well:  
missing ’ and the collection from the block variable.)

-Rob

Rob B. [http://agileconsultingllc.com](http://agileconsultingllc.com)  
removed\_email\_address@domain.invalid
