# Group by (2 -levels)

**URL:** <https://www.ruby-forum.com/t/group-by-2-levels/82277>\
**Category:** Rails\
**Created:** [January 18, 2007, 6:22pm UTC](https://www.ruby-forum.com/t/group-by-2-levels/82277 "2007-01-18T18:22:53Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![ryan](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/a8b319/32.png) [@ryan](https://www.ruby-forum.com/u/ryan)\
**Post date:** [January 18, 2007, 6:22pm UTC](https://www.ruby-forum.com/t/group-by-2-levels/82277/1 "2007-01-18T18:22:53Z")

</div>

My table looks like: make | model | year

And I’d like to display the info like:

Make 01  
Model 01  
Year 01  
Year 02  
Year 03  
Model 02  
Year 01  
Year 02

Make 02  
Model 01  
Year 01  
Year 02

etc…

I think group\_by will work for 1 level, but are there any ideas for a  
better solution?

Thank You,

---

<div class="post-metadata">

**Author:** ![ryan](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/a8b319/32.png) [@ryan](https://www.ruby-forum.com/u/ryan)\
**Post date:** [January 19, 2007, 9:06am UTC](https://www.ruby-forum.com/t/group-by-2-levels/82277/2 "2007-01-19T09:06:17Z")

</div>

Ryan wrote:

> My table looks like: make | model | year
> 
> And I’d like to display the info like:
> 
> Make 01  
> Model 01  
> Year 01  
> Year 02  
> Year 03  
> Model 02  
> Year 01  
> Year 02
> 
> Make 02  
> Model 01  
> Year 01  
> Year 02
> 
> etc…
> 
> I think group\_by will work for 1 level, but are there any ideas for a  
> better solution?
> 
> Thank You,

Better to roll your own solution in this multi level case.

class Vehicle \< ActiveRecord::Base  
def self.all\_sorted  
cars = find(:all)  
sorted\_cars = {}

```
  cars.each do |car|
    #ensure containers exist
    sorted_cars[car.make] ||= {}
    sorted_cars[car.make][car.model] ||= {}
    sorted_cars[car.make][car.model][car.year] ||= []

    #put the car in its place
    sorted_cars[car.make][car.model][car.year] << car
  end

  sorted_cars
end

```

end

Vehicle.all\_sorted[‘honda’][‘civic’][1996] #=\> Array of cars

Should do the trick.

---

<div class="post-metadata">

**Author:** ![ryan](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/a8b319/32.png) [@ryan](https://www.ruby-forum.com/u/ryan)\
**Post date:** [January 19, 2007, 9:39am UTC](https://www.ruby-forum.com/t/group-by-2-levels/82277/3 "2007-01-19T09:39:08Z")

</div>

Seems like a common problem - better have a look at this:

[http://www.ruby-forum.com/topic/93747#191513](http://www.ruby-forum.com/topic/93747#191513)
