【问题标题】:Get grouped values by multiple ids in ActiveRecord在 ActiveRecord 中按多个 id 获取分组值
【发布时间】:2018-09-30 04:02:39
【问题描述】:

抱歉英语不好))

我的 ruby​​ 代码中有一个 id 数组。

例子:

[[10], [], [10, 1, 3], []]

我可以通过保存分组在一个查询中从 MySQL 表 users 加载 User 模型吗?

例子:

[[#<User id=10>], [], [#<User id=10>, #<User id=1>, #<User id=3>], []]

环境:Ruby 2.5.1 |导轨 5 | MySQL

找到的解决方案之一:

我可以展平我的 id 数组并通过该数组将我的模型加载到哈希中:

hash = User.where(id: array.flatten).index_by(&:id)

然后,在迭代过程中,通过数组我可以像这样以正确的顺序从哈希加载我的对象:

array.each do |ids|
  users = ids.map { |id| hash[id] }
  # do smth
end

【问题讨论】:

  • 您的分组标准是什么?我认为活动记录只返回数组,但你可以使用 ruby​​ 来创建你想要的分组。
  • 您的示例输入和输出不匹配。
  • 我认为您至少需要扫描主数组并使用like this为每个元素调用数据库

标签: mysql sql ruby-on-rails ruby


【解决方案1】:

这很简单:对数组使用 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)

【讨论】:

  • 感谢您的回答!但我需要像这样保存我的分组:[[#&lt;User id=123&gt;], [], [&lt;#User id=123&gt;, #&lt;User id=1&gt;], [&lt;#User id=3&gt;, ...]] 在您的示例中,我将获得模型的 uniq 数组。
猜你喜欢
  • 1970-01-01
  • 2021-12-31
  • 1970-01-01
  • 1970-01-01
  • 2017-05-10
  • 1970-01-01
  • 2010-09-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多