Если я запускаю этот запрос в консоли rails,
def c
ids = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
users = User.all
members = Member.where(id: ids).includes(:locations)
user_id_to_member_id_mapping = {} # Not empty. hash that gives member_id for each userid
users.each do |user|
puts members.find_by(id: user_id_to_member_id_mapping[user.id]).location
end
end
запускается несколько запросов (запросов объектов-членов) (по одному для каждого значения i
).Члены уже находятся в памяти (members
переменная)?Как я могу получить данные, необходимые выше, чтобы сделать один запрос?
Member Load (0.2ms) SELECT `members`.* FROM `members` WHERE `members`.`id` IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) AND `members`.`id` = 1 LIMIT 1
ProfileAnswer Load (0.4ms) SELECT `profile_answers`.* FROM `profile_answers` WHERE `profile_answers`.`member_id` = 1
Member Load (0.4ms) SELECT `members`.* FROM `members` WHERE `members`.`id` IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) AND `members`.`id` = 2 LIMIT 1
ProfileAnswer Load (0.2ms) SELECT `profile_answers`.* FROM `profile_answers` WHERE `profile_answers`.`member_id` = 2
Member Load (0.2ms) SELECT `members`.* FROM `members` WHERE `members`.`id` IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) AND `members`.`id` = 3 LIMIT 1
ProfileAnswer Load (0.2ms) SELECT `profile_answers`.* FROM `profile_answers` WHERE `profile_answers`.`member_id` = 3
Member Load (0.2ms) SELECT `members`.* FROM `members` WHERE `members`.`id` IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) AND `members`.`id` = 4 LIMIT 1
ProfileAnswer Load (0.2ms) SELECT `profile_answers`.* FROM `profile_answers` WHERE `profile_answers`.`member_id` = 4
Member Load (0.2ms) SELECT `members`.* FROM `members` WHERE `members`.`id` IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) AND `members`.`id` = 5 LIMIT 1
ProfileAnswer Load (0.2ms) SELECT `profile_answers`.* FROM `profile_answers` WHERE `profile_answers`.`member_id` = 5
Member Load (0.4ms) SELECT `members`.* FROM `members` WHERE `members`.`id` IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) AND `members`.`id` = 6 LIMIT 1
Я не могу использовать member.each
, поскольку итератор находится в другом состоянии.