我正在尝试使用模型中的定义来总计所有“数量”列,如下所示:
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一样工作?
答案 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)