Ruby on Rails:如何在模型中正确定义方法以总计列?

时间:2010-08-26 13:39:17

标签: ruby-on-rails

我正在尝试使用模型中的定义来总计所有“数量”列,如下所示:

  def self.total
    self.all.collect(&:amount).sum
  end

有了它,“Recipe.total”按预期工作。但是,我正在使用一个传递“Recipe.find(:all)”的插件,我似乎无法将其传递给方法来查找总数。那就是:

Recipe.find(:all).total # doesn't work

有没有办法在我的模型中定义方法,使Recipe.find(:all).total像Recipe.total一样工作?

2 个答案:

答案 0 :(得分:5)

您可以将您的方法编写为:

def self.total
  self.sum(:amount)
end

然后您也可以将它与命名范围一起使用:

Recipe.total # without any scopes
Recipe.my_custom_named_scope.total # with your custom named scope

另一种变体是覆盖该模型的find方法:

def self.find(*args)
  result = super
  if args[0] && args[0] == :all
    def result.total
      self.sum(&:amount)
    end
  end
  result
end

然后你得到你想要的,你就可以写Recipe.find(:all).total

答案 1 :(得分:3)

查看Calculation Module

它有以下方法:总和,平均值,计数等......

它被烘焙到ActiveRecord。

所以你想写:

Recipe.sum(:total)

玩得开心!