2014-07-01 53 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

相關問題