Ruby on rails 如何将哈希添加到哈希中

Ruby on rails 如何将哈希添加到哈希中,ruby-on-rails,ruby,activerecord,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=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",         
   }    
如何执行此操作?

通过“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

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

@addresses = Address.select("id AS address_id, user_id, city, country").all
现在,地址模型散列的ID列不应与用户散列的ID列冲突。然后,您可以按照Neil Slater的建议,使用以下方法合并它们:

combo_hash = user_hash.merge(address_hash)

有一个
.merge
方法,它可以完成您想要的大部分工作。但是,您的示例哈希具有重复的键
“id”
,这在Ruby的哈希类中无法工作。如果没有重复id,只需
combo\u hash=user\u hash.merge(address\u hash)
Hi@NeilSlater当我这样做时,我会得到“未定义的方法` merge'for#”,为什么不在这里使用渴望加载的概念呢?像
@users=User.includes(:地址)。all
。现在这个对象有了用户和相关地址。现在,当您执行
@users.first.addresses
操作时,这将提供与哈希/返回对象中的第一个用户关联的所有地址。PS:我假设用户和地址模型之间存在一对多的关联。如果你更喜欢SQL,你可以使用连接。我是说