views:

235

answers:

1

I have a join table that I'm using to find available services for an order form; in that table is the utility_id and a company_id.

What I want is a group (hash) where the keys are the utility names and the values are hashes of the corresponding companies.

I got the following...

Service.find(:all).to_set.classify { |service| Utility.find(service.utility_id).name }

... which very nicely gives me a hash where the keys are the utility names, but the values are Sets of the Service records, not just the company names (I don't need the actual records), and I can't figure out how I'd make the hash I want:

# example of what I would like to have
{"electricity" => {"conEd" => 1, "Dominian" => 2}, "gas" => {"conEd" => 1}} 
# where the key is Utility.name, and the value-hash is {Company.name => Company.id}

How would I do this?

A: 

find(:all) suggests Rails to me, so assuming you have a HABTM between the Utility and Service models correctly, this snippet works for my test environment:

results = Hash.new
Utility.find(:all).each do |utility|
  results[utility.name] = Hash.new
  utility.companies.each do |company|
    results[utility.name][company.name] = company.id
  end
end
results

Which produces

{"Communications"=>{"InternetCo"=>2, "PhoneCo"=>1}, "Energy"=>{"ElectricCo"=>4, "GasCo"=>3, "OilCo"=>5}}
Jim Zajkowski
The HABTM relationship (I'm using has_many, :through) is actually between `Company` and `Utility`; `Service` is my join model. And yes, I am using Rails (forgot to mention that). How would I change what you wrote above to work with my setup?
neezer
Edited to conform to your model objects.
Jim Zajkowski