假设我有一个这样的模型:
class Surface < ActiveRecord::Base
attr_accessible :width, :length
def area
self.width * self.length
end
end
其中@surface.area
返回表面的面积。现在,假设我有许多名为 @surfaces
的曲面,并且我想对所有面积求和。我该怎么做?
我最喜欢的解决方案如下所示:
@surfaces.sum(:area)
但是它不起作用。那么我如何在 Rails 中调用 .sum()
或 .group()
或任何类似的虚拟属性上的函数呢?我想避免 .each do |surface|
调用。
提前致谢。
最佳答案
sum
会很乐意接受 SQL 表达式,而不仅仅是列名,因此您需要做的就是将 sum
方法转换为 SQL:
@surfaces.sum('width * height')
@surfaces.sum('surface.width * surface.height') # If you think other tables might be involved.
此外,模型上的类方法会混合到关系中(因为作用域和类方法实际上是同一件事),因此您可以添加一个类方法来配合实例方法:
class Surface < ActiveRecord::Base
def self.area
sum('surface.width * surface.height')
end
def area
self.width * self.length
end
end
并说:
@surfaces.area
通常最好让数据库处理您的数据的繁重工作,这就是它们的用途和擅长的地方。
关于ruby-on-rails - ruby on Rails 中的 sum() 或 group() 虚拟属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40385536/