Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

829
Vistas
ActiveRecord Query. Group by multiple columns from multiple tables
Attendance.joins(:user).group(:email, :name).count

The query above gives me the below results. "User 1" had 2 attendances and "User 2" had 6 attendance, plus I have access to the user name and email.

{["email@example.com", "User 1"]=>2, ["email2@example.com", "User 2"]=>6]}

This is great except I'd really like the User.id to be included as well. I can't group by the ID because then each record will be unique instead of being grouped by email and name. The below is what i'd like:

{[1, "email@example.com", "User 1"]=>2, [2, "email2@example.com", "User 2"]=>6]}

Any help would be appreciated.

Answer Attendance.joins(:user).group(:email, :name, 'attendances.user_id').count

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Attendance.joins(:user).group(:email, :name, 'attendances.user_id').count
over 4 years ago · Santiago Trujillo Denunciar

0

# collect required fields and group by email, name
grouped_attendance = Attendance.joins(:user).pluck(:id, :email, :name).group_by{|r| [r[1], r[2]]}

# calculate the counts
attendance_counts = grouped_attendance.each{|k,v| grouped_attendance[k] = v.count}

Depending on your setup, but above should be fast enough as you are not instantiating ActiveRecord objects.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda