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
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.