43

Example I have:

@test = Pakke.find([[4], [5]])

In my Pakke table I have a column named prismd

How do I sum the two values for the prismd columns for @test?

Rails beginner
  • 14,321
  • 35
  • 137
  • 257
  • 2
    You should definitely bring some order into your arrays. It's very confusing what you are actually trying to do and just trying until it seemingly works is not the best way to do it. Instead try to think what you really want to achieve and organise your data structure accordingly. Also splitting up your actual problem over 5 or more questions here will not help much.... – Holger Just Jan 16 '12 at 00:05
  • 1
    I will try. It is a bit complicated want I am trying to do. Just know I mainly want it to work because it have taken a lot of time finding the right solution. – Rails beginner Jan 16 '12 at 00:13

4 Answers4

67

You can summarize directly on the database by creating the respective SQL like this:

Pakke.sum(:prismd, :conditions => {:id => [4,5]})

On newer Rails versions (i.e. Rails >= 4.0), you can use an ActiveRecord queries more intuitively, such as:

Pakke.where(id: [4,5]).sum(:prismd)

See ActiveRecord::Calculations for more usage examples and general documentation.

Holger Just
  • 52,918
  • 14
  • 115
  • 123
44

ActiveRecord has a bunch of built-in calculation methods, including sum:

@test = Pakke.where(:id => [4, 5] ).sum(:prismd)
Jordan Running
  • 102,619
  • 17
  • 182
  • 182
  • 11
    FYI, **do not** use `.sum(&:prismd)`. This will complete the calculation via Ruby. Doing what @Jordan says will complete the calculation via SQL and is **much**, **much** faster. – Joshua Pinter Dec 07 '14 at 17:53
4
Pakke.find([[14], [15]]).map(&:prismd).sum
Conner
  • 30,144
  • 8
  • 52
  • 73
Rails beginner
  • 14,321
  • 35
  • 137
  • 257
  • 2
    This wouldn't be very efficient, since it would have to instantiate all of the records and then sum on the Ruby side rather than in the database directly. – KNejad Apr 17 '20 at 12:39
  • This utilizes ruby instead of sql. It might function, but there is a faster way provided by the lightning fast language of sql. – Thomas Feb 27 '23 at 21:57
1

test = Order.where(potential_student_id: potential_student.id).sum("total_price");

KevinLi
  • 131
  • 1
  • 4