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

sjs*_*jsc 4 ruby-on-rails

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

  def self.total
    self.all.collect(&:amount).sum
  end
Run Code Online (Sandbox Code Playgroud)

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

Recipe.find(:all).total # doesn't work
Run Code Online (Sandbox Code Playgroud)

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

les*_*est 5

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

def self.total
  self.sum(:amount)
end
Run Code Online (Sandbox Code Playgroud)

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

Recipe.total # without any scopes
Recipe.my_custom_named_scope.total # with your custom named scope
Run Code Online (Sandbox Code Playgroud)

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

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

然后你得到你想要的,你就能写出来Recipe.find(:all).total.