在哈希中检索数据

Retrieving data in a hash

我需要从 ActiveRecord 获取一些数据,我有以下两个表 Department 和 users 我有一个问题,我得到一个用户给我 user_ids 和电子邮件的哈希,现在我想创建以特定格式散列容器用户、部门和电子邮件。我试了很多map/select但还是想不出任何简单的方法。

class User < ApplicationRecord
  belongs_to :department
end

和部门

class Department < ApplicationRecord
  has_many :users
end

我从用户那里得到以下值

sample_params = [{ user_id: 1, email: 'example1@example.com' }, 
{ user_id: 5, email: 'example5@example.com' }, 
{ user_id: 13, email: 'example13@example.com'}]

现在我已经从数据库和其他数据中检索了部门,并加入了一个巨大的散列,这样我就可以将它添加到我的 class 中。我可以通过以下命令获取所有用户

users = User.where(id: sample_params.map{ |m| m[:user_id] })

如果我 运行 按照命令获得所有 user_id 和 project_id

,我将获得所有用户的整个 ActiveRecord 对象
users.map { |u| {user_id: u.id, department_id: u.department_id } }

我会得到这个

[{:user_id=>1, :department_id=>3}, 
{:user_id=>5, :department_id=>3}, 
{:user_id=>13, :department_id=>2}]

但我想创建以下哈希,有没有任何简单的方法可以直接使用查询或其他几行来完成,我可以尝试使用 Iteration 但这会很长很复杂。因为我还需要合并其中的电子邮件并添加一个项目而不是相同项目的多个 ID。

[
{department_id: 1, users: [{user_id: 1, email: 'example1@example.com'},
 {user_id: 5, email: 'example5@example.com'}]}, 
{department_id: 2, users: [{ user_id: 13, email: 'example13@example.com']

我这里使用的是示例数据,真实数据非常非常大,包括数百个用户和很多部门。

我觉得你不可能一下子搞定!让我们 运行 通过并尝试如何解决它。首先,我们不要在您的参数中使用地图,而是尝试另一种替代方法。删除以下行

users = User.where(id: sample_params.map{ |m| m[:user_id] })

用户关注行

User.where(id: sample_params.pluck(:user_id)).pluck(:department_id, :id).grou
p_by(&:first)

这将在一个查询中为您带来每个用户 ID 和部门分组

{3=>[[3, 1], [3, 5]], 2=>[[2, 13]]}

现在我们得到 department_id 和 user_id 所以我们将 运行 映射到它们上以获得第一个数组 department_id 和 user_id 在一个组中使用以下命令

data =
  User
  .where(id: sample_params.pluck(:user_id))
  .pluck(:department_id, :id)
  .group_by(&:first).map do |department_id, users|
    { department_id: department_id,
      users: users.map { |_, id| id } }
  end

这将为您提供部门和用户的哈希值

[{:department_id=>3, :users=>[1, 5]}, {:department_id=>2, :users=>[13]}]

现在你有了部门和用户的散列。所以让我们一起努力这是第二阶段,我将使用 select 从您的参数中获取电子邮件并将其合并到您的数据中。

result = []
data.each do |department|
  department_users = []
   department[:users].each do |user|
     emails = sample_params.select { |user| user[:user_id] == 1 }[0][:email];
     department_users << { id: user, emails: emails }
   end; result << {department_id: department[:department_id], users: department_users}
end

现在,如果您这样做 puts result[0],您将获得所需的哈希值。

{:department_id=>3, :users=>[{:id=>1, :emails=>"example1@example.com"}, {:id=>5, :emails=>"example1@example.com"}]}, {:department_id=>2, :users=>[{:id=>13, :emails=>"example1@example.com"}]}

这将解决问题,我知道有两个操作,但在单个操作中没有双重 sql 查询它正在工作,而且您也在更换您的电子邮件。我希望它能解决你的问题,任何能使它更简单的人将不胜感激。