I was wondering if there was a method in Rails that returns the sum of a
column. For example, I have a column called ‘score’ and writing a SQL
statement such a ‘select sum(score) from table_name’ does return the sum
of the values in the column. In the past (not too long ago being a
newbie), I defined all sorts of methods only to discover that Rails
(after reading Agile Web Dev) already had something much simpler (I
don’t mind since it’s helping me learn Ruby along the way).
My question is this, does Rails have any methods that can do this …
@points = self.find_by_sql(“select sum(score) from scores”)
points = @points #assigns first row
points = points.attributes #assigns as hash
points = points.values # pulls out the value
points = points.to_s #converts to string
points = points.to_i # converts to fixnum
Or am I wanting to be too concise. Also, if there isn’t a Rails way of
condensing the above, is there any shortcut in Ruby.
Thanks for any suggestions in advance!