Suppose to have the following table:
Product(id:integer, category:string, cost:float)
And you want to perform this query with activerecord
:
Product.select("cost + 1000 AS incremented_cost").group(:category).sum('incremented_cost')
ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR: column "incremented_cost" does not exist
The example is quite simplified, however it well represents the problem: how can I assign an alias to a modified field and the use it in an aggregate function?
My goal is to return an Activerecord_Relation where it is possible to compute aggregations on a alias field, possibly on a group. The problem is that "grouping" is conditional and I would like to keep the data pipeline.
select
method does not work because it does not change the fields names of a relation. If you use "AS" it is possible to access the alias (see link). However it does not work in aggregate functions.
See: http://apidock.com/rails/v4.1.8/ActiveRecord/QueryMethods/select
Using #inject
it is not a good solution for me, I don't want to deal with arrays.
For instance this code gives the right result, but it's not a good solution for me:
Product.select("cost + 1000 AS incremented_cost").inject(0) do |acc, record|
acc + record.incremented_cost
end