我有以下 2 个 rails 模型:
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
我正在尝试在配置文件上创建一个“顶级”范围,该范围根据相关用户记录收到的“赞成”票数对配置文件进行排序
投票是由用户为用户创建的。 “by”列表示投票的用户,“for”列表示收到投票的用户。我正在尝试获取获得最多选票的用户的个人资料。
这是我目前所得到的:
scope :top,
select("profile.*, count(votes.id) AS votes_count").
joins(:votes, :user).
order("votes_count DESC")
这不适用于以下错误:
ActiveRecord::StatementInvalid: PG::Error: ERROR: column "votes_count" does not exist
它也没有考虑“for”列
谁能帮帮我?
最佳答案
我相信你错过了一个分组。 这是您尝试执行的查询:
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')
关于sql - Rails 3 ActiveRecord 和 Postgres : order by count on association,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15478909/