简体   繁体   中英

How to Add Hash into Hash

i have a User Model and Address Model. when i do @user=User.all it returns

  {  "id" : "1",
    "firstname" : "test",
    "username" : "test",   
  },
  {  "id" : "2",
    "firstname" : "test1",
    "username" : "test2",       
  }  

and when i do @address =Address.all

{   "id" : "21",
    "user_id" : "1",
    "city" : "test",
    "country" : "test",   
  },
  {  "id" : "22",
     "user_id" : "2",
     "city" : "test1",
     "country" : "test2",       
  }  

i get above value

Now i want to merge both value that is @user and @ddress in a single Hash. like ex-

   {  "id" : "1",
     "firstname" : "test",
     "username" : "test",   
     "id" : "22",
     "user_id" : "1",
     "city" : "test1",
     "country" : "test2",   
    },
   {  "id" : "2",
     "firstname" : "test2",
     "username" : "test2", 
     "id" : "22",
     "user_id" : "2",
     "city" : "test1",
     "country" : "test2",         
   }    

How to do this?

Index one array by "id" into a hash:

users_by_id = {}
@users.each {|h| users_by_id[h['id']] = h}

Next step, merge into the second hash:

@address.map do |address| 
   # search the user with the same id
   u = users_by_id[address['user_id']]
   if u
     # rename 'id' key
     u['uid'] = u['id']
     address.merge(u)
   else
     address # no user matched!
   end
end

One possible way to solve this issue is to alias the duplicate column in the select clause. For your address model, when you pull up each record, you can do the following:

@addresses = Address.select("id AS address_id, user_id, city, country").all

Now the ID column of your address model hash should not conflict with the ID column of your user hash. You can then merge them as Neil Slater suggested, using:

combo_hash = user_hash.merge(address_hash)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM