简体   繁体   中英

How to apply find_by to elements of an array of arrays - Rails

I have the following array of arrays of 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.

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

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