Forum: Ruby on Rails Grouping of related records

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.
26f69df221203d2adc7bee524ba9c720?d=identicon&s=25 Marco Kotrotsos (Guest)
on 2007-02-28 21:29
Hey, goodevening to all.

I have something that I wonder if I can do better.

I have a list or records, employee records

Marco from Amsterdam
Silvia from Amsterdam
Enola from Rotterdam
Elisa From Utrecht

These are now shown as

Amsterdam
Marco
Amsterdam
Silvia
Rotterdam
Enola
Utrecht
Elisa

What I would really want is

Amsterdam
Marco
Silvia

Rotterdam
Enola

Utrecht
Elisa

So to have them grouped by the City from which they come from
Is there an elegant solution to this? I know a couple, but all seem like
nasty hacks (like putting all the cities up and query each and every
city)
Hope someone can help
Thank you
Kind regards,
Marco
2f9a03aa0fcfe945229cb6126eda2cb2?d=identicon&s=25 Philip Hallstrom (Guest)
on 2007-03-01 04:53
(Received via mailing list)
> Amsterdam
> Amsterdam
> Is there an elegant solution to this? I know a couple, but all seem like
> nasty hacks (like putting all the cities up and query each and every
> city)

Assuming that each record has name and city as attributes you could do
something like:

last_city = nil
@results.each do |r|
   if last_city != r.city then
     puts "\n" unless r == @results.first
     puts r.city
     last_city = r.city
   end
   puts r.name
end

My memory is there's a nifty way to do it in Ruby, but I can't recall
what
it is right now...
E3640176765dae2465d33ef6eb114691?d=identicon&s=25 bcparanj@gmail.com (Guest)
on 2007-03-01 07:29
(Received via mailing list)
class MyLister

 def initialize(city, names)
   @city = city
   @names = names
 end

 def to_s
  puts "#{@city}"
  @names.each  { |name| puts name }
 end
end


m = MyLister.new("Kansas", ["Andy", "Brady", "Cuddy"])
m.to_s

This prints:

Kansas
Andy
Brady
Cuddy

Any other elegant solution?
26f69df221203d2adc7bee524ba9c720?d=identicon&s=25 Marco Kotrotsos (Guest)
on 2007-03-01 10:04
That's nifty, but any idea what the Activerecord aquivalent would be?
Thanks!
Marco

bcparanj@gmail.com wrote:
> class MyLister
>
>  def initialize(city, names)
>    @city = city
>    @names = names
>  end
>
>  def to_s
>   puts "#{@city}"
>   @names.each  { |name| puts name }
>  end
> end
>
>
> m = MyLister.new("Kansas", ["Andy", "Brady", "Cuddy"])
> m.to_s
>
> This prints:
>
> Kansas
> Andy
> Brady
> Cuddy
>
> Any other elegant solution?
This topic is locked and can not be replied to.