Group by (2 -levels)


#1

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,


#2

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.


#3

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

http://www.ruby-forum.com/topic/93747#191513