# Sorting group\_by

**URL:** <https://www.ruby-forum.com/t/sorting-group-by/136435>\
**Category:** Rails\
**Created:** [May 2, 2008, 1:56am UTC](https://www.ruby-forum.com/t/sorting-group-by/136435 "2008-05-02T01:56:33Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![lelio98](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/6f9a4e/32.png) [@lelio98](https://www.ruby-forum.com/u/lelio98)\
**Post date:** [May 2, 2008, 1:56am UTC](https://www.ruby-forum.com/t/sorting-group-by/136435/1 "2008-05-02T01:56:33Z")

</div>

I have ran into a stumbling block sorting a group\_by

In my model, I have defined a method called “due\_by\_in\_words”, this  
method returns a hash with a :key and a :value based on a number of  
elsif statements.

{:key =\> 1, :value =\> ‘Overdue’}  
{:key =\> 2, :value =\> ‘Today’}  
etc…

In my controller I have:

@tickets\_due\_by = @tickets.group\_by { |t| t.due\_by\_in\_words[:key] }

Which is grouping based on the hashes :key, this is working very well.

What I want to do now, is to display the :value from the hash, in my  
view I have:

\<% @tickets\_due\_by.sort.each do |due\_by\_in\_words, tickets| %\>

## \<%= due\_by\_in\_words %\>
 \<% for ticket in tickets %\> HTML here... \<% end %\> \<% end %\>

This is, of course, only displaying the :key (1,2,3…), I would like  
to be able to access the :value of the hash, but it won’t be  
accessible to the view, at least I don’t think it will be. It seems  
to me that the “due\_by\_in\_words” will only contain the :key of the  
hash, and not the entire hash.

I want to be able to display the :value as a header of sorts

Any thoughts?

---

<div class="post-metadata">

**Author:** ![lelio98](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/6f9a4e/32.png) [@lelio98](https://www.ruby-forum.com/u/lelio98)\
**Post date:** [May 2, 2008, 2:53am UTC](https://www.ruby-forum.com/t/sorting-group-by/136435/2 "2008-05-02T02:53:17Z")

</div>

Alright. Couple things.

Tickets should have an attribute :due\_by that stores when it’s due.

due\_by should return a hash of due ids and descriptions. Keep in mind,  
when writing hashes, you don’t explicitly define :key and :value:  
@due\_by = {1 =\> ‘Overdue’, 2 =\> ‘Today’,…}

In your controller you should have:  
@tickets\_due\_by = @tickets.group\_by{|t| t.due\_by}

Then in your view  
\<% @tickets\_due\_by.sort.each do |due\_by\_id, tickets| %\>

## \<%= @due\_by[due\_by\_id] %\>
 \<% for ticket in tickets %\> \<%= ticket.name %\> \<% end %\> \<% end %\>

Basically it involves writing your hash correctly 🙂

ESPNDev
