Forum: Ruby on Rails group by issue

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.
934f858e451cf9b771996b2940cd696b?d=identicon&s=25 Raj Singh (dorelal)
on 2007-04-20 18:29
(Received via mailing list)
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 %> <br />
<% 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?
Ef3aa7f7e577ea8cd620462724ddf73b?d=identicon&s=25 Rob Biedenharn (Guest)
on 2007-04-20 21:00
(Received via mailing list)
On Apr 20, 2007, at 12:29 PM, Neeraj Kumar 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 %> <br />
<% end %>

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

-Rob

Rob Biedenharn    http://agileconsultingllc.com
Rob@AgileConsultingLLC.com
This topic is locked and can not be replied to.