如何将哈希加入哈希

时间:2013-06-10 19:01:56

标签: ruby-on-rails ruby activerecord

我有一个用户模型和地址模型。  当我做@ user = User.all  它返回

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

当我做@address =Address.all

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

我超越了价值

现在我想在单个Hash中合并@user和@ddress的值。  像前 -

   {  "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",         
   }    

怎么做?

2 个答案:

答案 0 :(得分:1)

将一个数组索引为" id"哈希:

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

下一步,合并到第二个哈希:

@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

答案 1 :(得分:1)

解决此问题的一种可能方法是在select子句中为复制列添加别名。对于您的地址模型,当您提取每条记录时,您可以执行以下操作:

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

现在,地址模型哈希的ID列不应与用户哈希的ID列冲突。然后你可以使用:

将它们合并为Neil Slater建议的
combo_hash = user_hash.merge(address_hash)
相关问题