Here is my array:
finalcount = Vote.where(:month => month, :year => year, :vote_id => vote.id).count
I'd like to use group_by
(I think?) to group the votes by user_id
(which each vote has), and then return the user_id
with the highest votes.
Any ideas how I can do this?
Have you tried the group
method?
finalcount = Vote.where(:month => month, :year => year, :vote_id => vote.id).group(:user_id).count
will give you a Hash
where the keys are the user_id
and the values are the count
. You can then call max
on this result to get a two-element array containing the user_id
and the count
.
Here's an example from an app I have handy, where I use the result of the calculation to find the correct model instance and read properties from it:
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"
I think what you really want is this:
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)
This will grab the user_id and count of votes they have, but only return the one with the most votes.
Why did your originall call have :vote_id => vote.id
? Does your Vote model really have a column named vote_id
and is it different than it's normal id
?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With