I searched quite a lot but can't my head around this one.
I have a model which is related to three other models. Let's call it cities. Cities do have a continent, a country and region.
When I select some cities I want to get back an OrderedHash or an array which looks like this:
{ 'Continent 1' => {'Country 1' => { 'Region 1' => { 'City 1', 'City 2' }}}, 'Continent 2' ...}
How can I do this?
Just group by region:
cities_by_region = City.all(:group => :region)
# set up an automatic 3-level hash...
result = Hash.new { |h,k| h[k] = Hash.new { |h,k| h[k] = {}}}
cities_by_region.each do |region, cities|
country = region.country
result[country.continent.name][country.name][region.name] = cities
end
Note that this doesn't employ sorting, but it can be easily adapted to do. Keep in mind that the insertion order of hashes is only retained in Ruby 1.9+.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With