简体   繁体   English

如何将 find_by 应用于数组数组的元素 - Rails

[英]How to apply find_by to elements of an array of arrays - Rails

I have the following array of arrays of user_ids :我有以下user_ids数组:

@host_and_guest = [
  ["1299d9c9-e5c9-4e49-b0ff-b986c415eee8", "346b5c2f-a459-4c4f-8193-e0928c86c66c"],
  ["1299d9c9-e5c9-4e49-b0ff-b986c415eee8", "346b5c2f-a459-4c4f-8193-e0928c86c66c"],
  ["1299d9c9-e5c9-4e49-b0ff-b986c415eee8", "346b5c2f-a459-4c4f-8193-e0928c86c66c"],
  ["1299d9c9-e5c9-4e49-b0ff-b986c415eee8", "1299d9c9-e5c9-4e49-b0ff-b986c415eee8"]
] 

and I would like to apply User.find_by(id: XXXX).pluck(:longitude, :latitude,:city) to each of the user_id in order to create a another array of longitude, latitude, and city for each of the sub-array.我想将User.find_by(id: XXXX).pluck(:longitude, :latitude,:city)应用于每个user_id ,以便为每个子项创建另一个经度、纬度和城市数组-大批。

Is there an efficient way to do so please ?有没有一种有效的方法可以做到这一点?

users = User.where(id: @host_and_guest.flatten)
            .pluck(:id, :longitude, :latitude, :city)
            .group_by(&:first) # creates hash with id as keys

@host_and_guest.map do |pair|
  # replace pair with array of 
  # [[longitude, latitude, city], [longitude, latitude, city]]
  pair.map { |id| users[id]&.drop(1) }
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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