ruby – How to refactor my long method of rails

I have wrote following solution for one answer but I want to refactor to make it more simple and readable.

I am receiving params

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

I want to create following hash to replace emails received from params

(
{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')

I am retrieving data from db using following codes

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

and then I am creating hash using following

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

How can I refactor to get following benefits

  • Easy to read
  • less number of lines
  • Performance It has one query of sql so not an issue but on memory I am saving all in array.