Rails + activerecord: how to create a hash from a table with a specific field value as a key

Given a ZipCodeInfos table with fields zipcode, state, city (all rows), where zipcode is unique:

zipcode,city,state "10000", "Fooville", "AA" "10001", "Smallville", "AA" "10002", "Whoville", "BB" 

What is the fastest way to generate a hash object of the whole table, where zipcode is such a key:

 { "10000" => {:city => "Fooville", :state => "AA" }, "10001" => {:city => "Smallville", :state => "AA" }, "10002" => {:city => "Whoville", :state => "BB" } } 

I know that for this record I can use. Zipcode.first.attributes to generate a hash with a key, pairs of field name values, field values, for example Zipcode.first.attributes gives me

 {"id" => 1, "zipcode" => "10000", "city" => "Fooville", "state => "AA" } 

But, with the exception of brute force, repeated across each record (via .map), I cannot figure out how to create the desired hash using zipcode as the key for each node hash.

Is this the best I could think of, and I suspect there is great ruby ​​kindness that is faster?

 zip_info_hash = {} ZipCodeInfo.all.map{|x| zip_info_hash[x.zip] = {'state' => x.state, 'city' => x.city }} 
+4
source share
3 answers

You can also try:

 ZipCodeInfos.all.group_by &:zipcode 

you will receive a zip hash into an array of activating ZipCodeInfos statements.

+1
source

You can use the injection method. This is what I usually use.

 def visitors_name_email visitors.inject({}) do |result, visitor| result.merge(visitor.name => visitor.email) end end 
0
source

I can't think of a way to avoid map here. I would only make some minor changes to your code:

 zip_info=Hash[*ZipCodeInfo.all .map{|x| [x.zip, {:city => x.city, :state => x.state}]} .flatten] 
0
source

Source: https://habr.com/ru/post/1490956/


All Articles