(对不起,英语不好)
我的红宝石代码中有一个ids数组。
示例:
[[10], [], [10, 1, 3], []]可以通过保存分组从User表users在一个查询中加载users模型吗?
示例:
[[#<User id=10>], [], [#<User id=10>, #<User id=1>, #<User id=3>], []]环境:Ruby2.5.1\ Rails 5= MySQL
已找到的解决方案之一:
我可以扁平I数组,并通过该数组将模型加载到散列中:
hash = User.where(id: array.flatten).index_by(&:id)然后,在迭代期间,通过数组,我可以按正确的顺序从散列加载对象,如下所示:
array.each do |ids|
  users = ids.map { |id| hash[id] }
  # do smth
end发布于 2018-04-20 10:45:32
这很简单:对数组使用扁平方法:
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)https://stackoverflow.com/questions/49924657
复制相似问题