我有两个模型 - Parent
和Params
,其中parent has_many params
目前,我的方法看起来像(不是它在Parent类下):
def total_sum
params.select(
'params.*, (
SUM(mono_volume_annular) +
SUM(day_volume_annular) +
SUM(night_volume_annular) +
SUM(exclusive_volume_annular)
) AS summed_volume_annular'
).group('params.id').sum(&:summed_volume_annular)
end
如何改进此SQL查询以摆脱.sum(&:summed_volume_annular)
方法调用?
如果我在没有将:summed_volume_annular
转换为proc的情况下尝试对其进行汇总,我会收到此错误:ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR: column "summed_volume_annular" does not exist
一个有趣的说明 - 如果我将尝试保存此查询的结果
params.select('(
SUM(mono_volume_annular) +
SUM(day_volume_annular) +
SUM(night_volume_annular) +
SUM(exclusive_volume_annular)
) AS summed_volume_annular'
)
我会得到这个对象[#<Parameter:0x00000009f1c7d8 id: nil>]
奇怪summed_volume_annular
缺席......
答案 0 :(得分:1)
我会做这样的事情:
def total_sum
columns_to_sum = %w(mono_volume_annular day_volume_annular night_volume_annular
exclusive_volume_annular)
sum = columns_to_sum.map{ |col| "COALESCE(#{col}, 0)" }.join(' + ')
Params.sum(sum)
end