Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum on multiple columns with Activerecord

I am new to Activerecord. I want to do sum on multiple columns of a model Student. My model student is like following:

 class Student < ActiveRecord::Base
   attr_accessible :class, :roll_num, :total_mark, :marks_obtained, :section
 end

I want something like that:

 total_marks, total_marks_obtained = Student.where(:id=>student_id).sum(:total_mark, :marks_obtained)

But it is giving following error.

NoMethodError: undefined method `except' for :marks_obtained:Symbol

So I am asking whether I have to query the model two times for the above, i.e. one to find total marks and another to find marks obtained.

like image 634
Joy Avatar asked Feb 20 '14 18:02

Joy


1 Answers

You can use pluck to directly obtain the sum:

Student.where(id: student_id).pluck('SUM(total_mark)', 'SUM(marks_obtained)')
# SELECT SUM(total_mark), SUM(marks_obtained) FROM students WHERE id = ?

You can add the desired columns or calculated fields to pluck method, and it will return an array with the values.

like image 154
AlexGuti Avatar answered Sep 17 '22 09:09

AlexGuti