Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I calculate the sum of a boolean column in Ruby on Rails

I have a column with boolean values and would like to use the 'sum' function to calculate a total. This column is used for getting a vote count similar to Stack Overflow or reddit.

Here's my code

votes = Vote.all
total = votes.sum(:direction)
puts' ....................' + total.to_s

And here's my error...

undefined method `+' for #<Vote:0x000000047c9170>

Any help is appreciated

like image 836
Jakcst Avatar asked Jan 31 '26 19:01

Jakcst


1 Answers

A sum of a boolean value? I'd just count the values with either direction=false or direction=true

total_down = Vote.where(direction: false).count #down vote
total_up = Vote.where(direction: true).count #up vote
puts "....... #{total_up} .... #{total_down}"
like image 115
Anthony Alberto Avatar answered Feb 03 '26 08:02

Anthony Alberto