2014-07-01 124 views
1

此功能...Rails中未定义的局部变量或方法to_a?

class Invoice < ActiveRecord::Base 

    def self.open_subtotal 
    sum{ |i| i.open_amount/(1.00 + i.tax_rate/100.00) } 
    end 

end 

...让我用Rails 4.0.2的错误:

弃用警告:调用#sum与块已被弃用,将在Rails中被删除4.1。如果要对元素数组执行求和计算,请使用to_a.sum(&block)

当我在sum之前添加to_a时,出现undefined local variable or method to_a错误。

写这个的正确方法是什么?

+1

你在什么总结? – apneadiving

+1

你为什么要花钱在花车上? http://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency –

+0

@MichalSzyndel:其实我所有的金钱价值都保存为数据库中的“小数”。上面的代码会搞砸吗? – Tintin81

回答

1

这会工作:

def self.open_subtotal 
    all.to_a.sum { |i| i.open_amount/(1.00 + i.tax_rate/100.00) } 
end 

但你可能可以概括在SQL(假设open_amounttax_rate在你invoices表中的字段):

def self.open_subtotal 
    sum("open_amount/(1 + tax_rate/100)") 
end 
+0

两者都像魅力一样工作,非常感谢。 – Tintin81

相关问题