ruby-on-rails - Rails 中未定义的局部变量或方法 to_a?

标签 ruby-on-rails ruby activerecord

这个函数...

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/

相关文章:

ruby-on-rails - 将 ruby​​ on rails 应用程序从 sqlite 转换为 postgresql

ruby-on-rails - 如何在 Rails 中完全删除模型及其关联?

ruby - rvm 安装 : is_a_function: command not found

php - 事件记录和 PHP : the best way to define different associations between two models

ruby-on-rails - 在 JBuilder 中生成嵌套的 JSON 数组

ruby-on-rails - 我向 ActiveRecord::MigrationContext#new 中的 schema_migration 传递什么

ruby - node-webkit 等同于 sinatra?

ruby - 分隔包含逗号和双引号的 csv 文件的最佳方法是什么?

ruby - 在模块中使用 FactoryGirl 时出现未初始化常量 (NameError)

ruby-on-rails - 从 Rails postgres 数据库中删除重复项