抱歉英语不好))
我的ruby代码中有一个id数组。
示例:
[[10], [], [10, 1, 3], []]
我可以通过保存分组在一个查询中从MySQL表User
加载users
模型吗?
示例:
[[#<User id=10>], [], [#<User id=10>, #<User id=1>, #<User id=3>], []]
环境:Ruby 2.5.1 | Rails 5 | MySQL的
找到解决方案之一:
我可以展开我的数组,并将该数组加载到哈希:
hash = User.where(id: array.flatten).index_by(&:id)
然后,在迭代期间,通过数组我可以按照正确的顺序从哈希加载我的对象:
array.each do |ids|
users = ids.map { |id| hash[id] }
# do smth
end
答案 0 :(得分:0)
这很简单:对数组使用flatten方法:
ids = [[123], [], [123, 1, 3, 4], [70, 80]]
user_ids = ids.flatten.reject(&:blank?).uniq
users = User.where(id: user_ids)
编辑: 根据您的需要,不是最佳(递归)方法:
def map_users_by_id(ids_array:, users:)
result = []
ids_array.each do |array_element|
if (array_element).is_a? Array
result << map_users_by_id(ids_array: array_element, users: users)
else
result << users[array_element]
end
end
return result
end
ids = [[123], [], [123, 1, 3, 4], [70, 80]]
user_ids = ids.flatten.reject(&:blank?).uniq
users = Hash[User.where(id: user_ids).map{|user|[user.id, user]}]
result = map_users_by_id(ids_array: ids, users: users)