0

I'm getting an error when i'm trying to do a condition and sum my other column

@dolars =Policy.find(:all ,:conditions=>"type_money = '1' ").sum(&:amount_ensure)

My table

Policies 
    |id|  |type_money| |amount_ensure|
   integer   integer     integer 

My log is showing this

nil can't be coerced into Fixnum
.rvm/gems/ruby-1.8.7-p370/gems/activesupport-2.3.5/lib/active_support/whiny_nil.rb:52:in `+'
.rvm/gems/ruby-1.8.7-p370/gems/activesupport-2.3.5/lib/active_support/core_ext/enumerable.rb:61:in `sum'
.rvm/gems/ruby-1.8.7-p370/gems/activerecord-2.3.5/lib/active_record/attribute_methods.rb:211:in `inject'
.rvm/gems/ruby-1.8.7-p370/gems/activesupport-2.3.5/lib/active_support/core_ext/enumerable.rb:61:in `each'
.rvm/gems/ruby-1.8.7-p370/gems/activesupport-2.3.5/lib/active_support/core_ext/enumerable.rb:61:in `inject'
.rvm/gems/ruby-1.8.7-p370/gems/activesupport-2.3.5/lib/active_support/core_ext/enumerable.rb:61:in `sum'
.rvm/gems/ruby-1.8.7-p370/gems/activesupport-2.3.5/lib/active_support/core_ext/enumerable.rb:59:in `sum'

i'm trying to do this:

SELECT id, SUM(amount_ensure) As dolars,type_money
FROM Policies
WHERE type_money= "1"

The code in my controller should work but i don't know what happened

Someone can help me ? i will really appreciate all help

Charlie Brown
  • 219
  • 3
  • 10

3 Answers3

2

Use this

 @dolars = Policy.sum(:amount_ensure ,:conditions=>"type_money = '1' ")

The above query performs the summation in sql itself

When you call sum after find it sums the records fetched from the query.

tihom
  • 7,923
  • 1
  • 25
  • 29
1

You have a nil value for #amount_ensure somewhere.

Maybe this will make it more clear, in irb:

2.0.0p195 :001 > [1,2,3,4,nil].reduce(&:+)
TypeError: nil can't be coerced into Fixnum
    from (irb):1:in `+'
    from (irb):1:in `each'
    from (irb):1:in `reduce'
    from (irb):1
    from /Users/nick/.rvm/rubies/ruby-2.0.0-p195/bin/irb:16:in `<main>'
Nick Veys
  • 23,458
  • 4
  • 47
  • 64
  • Well i used this in my last example and worked with the same sintaxis but i don't know what happen here – Charlie Brown Sep 24 '13 at 04:00
  • This worked for me @dolars= Policy.find(:all ,:conditions=>"mount_type = '0'").sum(&:mount). But is not working my conditions that i posted – Charlie Brown Sep 24 '13 at 04:01
1

Try using the inject method, you could also cast .to_f so that nils are zeroed out.

@dolars =Policy.where(:type_money => 1).inject(0) { |sum, policy| sum += policy.amount_ensure.to_f }
derekyau
  • 2,936
  • 1
  • 15
  • 14