0

当我尝试做一个条件并对我的另一列求和时出现错误

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

我的桌子

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

我的日志显示这个

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'

我正在尝试这样做:

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

我的控制器中的代码应该可以工作,但我不知道发生了什么

有人可以帮助我吗?我将非常感谢所有帮助

4

3 回答 3

2

用这个

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

上面的查询在sql本身中执行求和

当您sumfind它汇总从查询中获取的记录之后调用时。

于 2013-09-24T04:05:23.027 回答
1

nil对某个地方有价值#amount_ensure

也许这会让它更清楚,在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>'
于 2013-09-24T03:45:10.007 回答
1

尝试使用注入方法,您也可以强制转换 .to_f 以便将 nil 清零。

@dolars =Policy.where(:type_money => 1).inject(0) { |sum, policy| sum += policy.amount_ensure.to_f }
于 2013-09-24T03:51:49.533 回答