stewart715
stewart715

Reputation: 5647

ActiveRecord summing columns

I would like to get the sum of multiple columns on a row of a table inside of a map, but sum only works on a model selection like this:

columns = 'col1 + col2 + col3'

Model.all.map do |model|
  Model.where(:id => model.id).sum(columns)
end

I'm trying to do this, so I don't have to access the database again and obviously it does not work:

columns = 'col1 + col2 + col3'

Model.all.map do |model|
  model.sum(columns)
end

Any ideas or tricks on how to do this? Keep in mind, columns must be used as the values of columns will change based on several criteria.

Upvotes: 0

Views: 173

Answers (1)

Stefan
Stefan

Reputation: 114138

You can't use SQL queries outside the database. However, if I understand your question correctly, something like this should work:

columns = 'col1 + col2 + col3'

Model.select("*, #{columns} AS my_sum").map do |model|
  model.my_sum  # the calculated sum
end

Make sure to properly escape your custom SQL queries.

Upvotes: 2

Related Questions