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

ruby-on-rails – Ruby on Rails:如何在模型中正确定义方法以总计列?,第1张

概述我正在尝试使用模型中的定义总计所有“数量”列,如下所示: def self.total self.all.collect(&:amount).sum end 有了它,“Recipe.total”按预期工作.但是,我正在使用一个传递“Recipe.find(:all)”的插件,我似乎无法将其传递给方法来查找总数.那是: Recipe.find(:all).total # doesn't 我正在尝试使用模型中的定义来总计所有“数量”列,如下所示:

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一样工作?

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

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

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

Recipe.total # without any scopesRecipe.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  resultend

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

总结

以上是内存溢出为你收集整理的ruby-on-rails – Ruby on Rails:如何在模型中正确定义方法以总计列?全部内容,希望文章能够帮你解决ruby-on-rails – Ruby on Rails:如何在模型中正确定义方法以总计列?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1285739.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-09
下一篇 2022-06-09

发表评论

登录后才能评论

评论列表(0条)

保存