ruby on rails - Active Record or SQL query for leaderboard (postgres rank and sum) -
i looking or creating advanced query in rails/active record (or sql using postgres) contest. i have contest table, users table , activities table. contests have many users (participants) , users have many activities. each activity has points, 'trackable_type', , other attributes. what want selected: - first_name users table - last_name users table - sum of points each user total_contest_points - count of activities have type 'course' each user total_contest_courses - results returned ranked total_contest_points , total_contest_courses i have taken @ postgres_ext gem , tried writing sql, can't seem ranking work. here's have far: time_range = start_time..end_time contestants = participants.joins(:activities).where('activities.created_at' => time_range).select(" users.id, users.first_name, users.last_name, sum(activities.points) total_contest_points, sum( case when activities.trackable_type='course' ...