Rails 3 ActiveRecord& Postgres:按关联顺序排序

时间:2013-03-18 14:12:14

标签: sql ruby-on-rails ruby-on-rails-3 postgresql activerecord

我有以下2种导轨型号:

class Profile < ActiveRecord::Base
  belongs_to :user

  has_many :votes, through: :user

  default_scope includes(:user)

end

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

我正在尝试在个人资料上创建一个“顶级”范围,根据相关用户记录收到的“for”投票数量对个人资料进行排序

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

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

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

这不适用于以下错误:

  

ActiveRecord :: StatementInvalid:PG ::错误:错误:列   “votes_count”不存在

它也不会考虑“for”列

任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分: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;

所以,让我们把它变成一个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')

答案 1 :(得分:2)

ActiveRecord方式

Profile.joins(:votes).group("profiles.id").order("count(profiles.id) DESC")