Forum: Ruby on Rails group by (2 -levels)

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.
Ryan (Guest)
on 2007-01-18 19:22
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,
Alex W. (Guest)
on 2007-01-19 10:06
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.
Andrew S. (Guest)
on 2007-01-19 10:39
Seems like a common problem - better have a look at this:

http://www.ruby-forum.com/topic/93747#191513
This topic is locked and can not be replied to.