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
Attendance.joins(:user).group(:email, :name, 'attendances.user_id').count
# 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.