[Rails] Using find_by_sql to get the sum of a column

Jérôme L eugenol at gmail.com
Sun Jan 8 20:50:59 GMT 2006


On 1/7/06, richard downe <rmdowne at yahoo.com> wrote:

> def self.total_points
>         @points = self.find_by_sql("select sum(score) from scores")
>         points = @points[0] #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
> end
>
> 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.

def self.total_points
  @points = self.count_by_sql("SELECT SUM(score) FROM scores")
end

and you'll get a fixnum, non conversion needed !


More information about the Rails mailing list