0

我有一个用户模型和地址模型。当我做 @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",       
  }  

我得到高于价值

现在我想将@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",         
   }    

这个怎么做?

4

2 回答 2

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
于 2013-06-10T19:10:24.107 回答
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)
于 2013-06-10T19:14:52.253 回答