Ruby on Rails request with sum and group?

Given the following model:

class Vote < ActiveRecord::Base attr_accessible :user_id, :vote_for_id, :voting_category_id, ,:points_earned belongs_to :user belongs_to :vote_for belongs_to :voting_category 

I would like to know how to make a query for a PostgreSQL database that returns a leading board. In other words, the total score for each user, sorted from first to last?

So far, I:

Votes.sum(:points_earned).group(:user_id, :id).order(:points_earned)

Thanks in advance

+4
source share
2 answers

Decision

The following query works on mysql and postgress.

 Vote. joins(:user). select('users.*, sum(points_earned) as total'). group('user_id'). order('total DESC'). limit(20) 
+2
source

This should return you a list of the top 20 users with the most points in descending order.

 Vote. joins(:user). select('*, sum(points_earned) as total'). group('user_id'). order('total DESC'). limit(20) 
+6
source

Source: https://habr.com/ru/post/1494377/


All Articles