ruby-on-rails – Ruby on Rails:如何在模型中正确定义方法以总
发布时间:2020-12-17 02:51:21 所属栏目:百科 来源:网络整理
导读:我正在尝试使用模型中的定义来总计所有“数量”列,如下所示: def self.total self.all.collect(:amount).sum end 有了它,“Recipe.total”按预期工作.但是,我正在使用一个传递“Recipe.find(:all)”的插件,我似乎无法将其传递给方法来查找总数.那是: Reci
我正在尝试使用模型中的定义来总计所有“数量”列,如下所示:
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 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. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |