这是我的数组:
finalcount = Vote.where(:month => month, :year => year, :vote_id => vote.id).count
我想使用
group_by
(我认为是这个?)按user_id
(每个投票都有)对投票进行分组,然后返回获得最高投票的user_id
。 有什么办法可以做到这一点吗?这是我的数组:
finalcount = Vote.where(:month => month, :year => year, :vote_id => vote.id).count
group_by
(我认为是这个?)按user_id
(每个投票都有)对投票进行分组,然后返回获得最高投票的user_id
。 有什么办法可以做到这一点吗?你尝试过使用group
方法吗?
finalcount = Vote.where(:month => month, :year => year, :vote_id => vote.id).group(:user_id).count
将会给你一个Hash
,其中键是user_id
,值是count
。然后你可以在这个结果上调用max
方法,以获取包含user_id
和count
的两个元素的数组。
这里有一个我手头上的应用程序的示例,我使用计算结果找到正确的模型实例并读取其属性:
ruby-1.9.2-p136 :001 > ExternalPost.group(:service_id).count
=> {18=>1, 19=>1, 21=>4}
ruby-1.9.2-p136 :002 > ExternalPost.group(:service_id).count.max
=> [21, 4]
ruby-1.9.2-p136 :003 > Service.find(ExternalPost.group(:service_id).count.max.first).user.first
=> "Brandon"
我认为您真正需要的是这个:
Vote.select("votes.user_id, count(votes.id)").
where(:month => month, :year => year, :id => vote.id).
group("votes.user_id").
order("count(votes.id) DESC").
limit(1)
vote_id
user_id
...
这应该返回一个数组,其中第一个元素是得到最多投票的用户ID,第二个元素是该用户ID的计数。
Vote.group(:user_id).count.max{|a, b| a.last <=> b.last}