这个函数...
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 中给我一个错误:
DEPRECATION WARNING: Calling #sum with a block is deprecated and will be removed in Rails 4.1. If you want to perform sum calculation over the array of elements, use
to_a.sum(&block)
.
当我在 sum
之前添加 to_a
时,我得到一个 undefined local variable or method to_a
错误。
正确的写法是什么?
最佳答案
显然这是现在的做法......
select('sum(invoices.open_amount / (1.00 + invoices.tax_rate / 100.00) as open_subtotal')[0][:open_subtotal]
这会在数据库级别进行计算,将其附加为新属性 open_subtotal
,然后您可以从选择的第一个实例中检索该属性。
取自此博客.. http://stim371.github.io/blog/2014/02/12/deprecating-blocks-on-activerecord-count-and-sum/
关于ruby-on-rails - Rails 中未定义的局部变量或方法 to_a?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24511368/