Ruby On Rails用sum和group查询?

ipe*_*sus 4 ruby ruby-on-rails

鉴于以下模型:

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
Run Code Online (Sandbox Code Playgroud)

我想知道如何查询PostgreSQL数据库,它返回一个排行榜.换句话说,每个用户的points_earned总和,从头到尾排序?

到目前为止,我有:

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

提前致谢

cry*_*o28 6

这应该返回给你一个前20名用户的列表,这些用户的point_earned降序最多

Vote.
  joins(:user).
  select('*, sum(points_earned) as total').
  group('user_id').
  order('total DESC').
  limit(20)
Run Code Online (Sandbox Code Playgroud)