Rails 3 ActiveRecord和Postgres:按关联计数

Gid*_*eek 2 sql postgresql activerecord ruby-on-rails ruby-on-rails-3

我有以下2种导轨型号:

class Profile < ActiveRecord::Base
  belongs_to :user

  has_many :votes, through: :user

  default_scope includes(:user)

end
Run Code Online (Sandbox Code Playgroud)

class Vote < ActiveRecord::Base
  attr_accessible :by, :for

  belongs_to :by, class_name: "User"
  belongs_to :for, class_name: "User"

  validates :by, :for, presence: true

  validates_uniqueness_of(:by, scope: :for)
end
Run Code Online (Sandbox Code Playgroud)

我正在尝试在Profile上创建一个"顶部"范围,根据相关用户记录收到的"for"投票数量对Profiles进行排序

用户为用户创建投票."by"列表示投票的用户,"for"栏表示已收到投票的用户.我正在尝试获得获得最多选票的用户的个人资料.

这是我到目前为止所得到的:

   scope :top,
    select("profile.*, count(votes.id) AS votes_count").
    joins(:votes, :user).
    order("votes_count DESC")
Run Code Online (Sandbox Code Playgroud)

这不适用于以下错误:

ActiveRecord :: StatementInvalid:PG ::错误:错误:列"votes_count"不存在

它也不考虑"for"列

谁能帮我吗 ?

MrT*_*rus 8

我相信你错过了一个分组.这是您要尝试的查询:

select profiles.*, count(votes.id) as votes_count 
  from profiles 
  left join votes on votes.for_id = profiles.user_id 
  group by profiles.id 
  order by votes_count desc;
Run Code Online (Sandbox Code Playgroud)

那么,让我们把它变成一个ActiveRecord范围:

scope :top, joins('left join votes on votes.for_id = profiles.user_id').
  select('profiles.*, count(votes.id) as votes_count').
  group('profiles.id').
  order('votes_count desc')
Run Code Online (Sandbox Code Playgroud)