Grouping of related records


#1

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


#2

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…


#3

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?


#4

That’s nifty, but any idea what the Activerecord aquivalent would be?
Thanks!
Marco

removed_email_address@domain.invalid 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?