Hi, in my project I needed to manage a set of query that fondamentally was a great sql union. I had a cycle that was running a query, and the resultant recordset was added to a variable with the += method. After some attempts I setted this var as Array because I found that the sum of ActiveRecord::Relation gave me an Array of objects!
But this was only half the job: I needed to work on that Array with aggregation function as sum and found nothing to help me than write my own code.
So the idea!
The sum of ActiveRecord::Relation objects returns a special Union object? This object act as a memory table and expose methods like select, ,find, group, sum, average and all the other valid for AR::Model object, the difference is that the fields of this “table” will be created at runtime, based on the first AR::Relation object passed to and all the other AR::Relation added need to have the same structure.
In this manner i wiil be easy to do
@recs = Union.new Model1.each do |m1| @recs += Model2.select…where…(:att1=>m1.attr) #what will be necessary end
@recs.select(‘f1 as myfield, sum(f2) as total, average(f3) as avv’).group(:id_field)
I propose this class because I am not able to achieve.
Thanks for read Giorgio