# Idea to manipulate the ActiveRecord Relation

**URL:** <https://discuss.rubyonrails.org/t/idea-to-manipulate-the-activerecord-relation/67773>\
**Category:** rubyonrails-talk\
**Created:** [September 11, 2013, 5:35pm UTC](https://discuss.rubyonrails.org/t/idea-to-manipulate-the-activerecord-relation/67773 "2013-09-11T17:35:09Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![giorgio.borri](https://avatars.discourse-cdn.com/v4/letter/g/8797f3/32.png) [@giorgio.borri](https://discuss.rubyonrails.org/u/giorgio.borri)\
**Post date:** [September 11, 2013, 5:35pm UTC](https://discuss.rubyonrails.org/t/idea-to-manipulate-the-activerecord-relation/67773/1 "2013-09-11T17:35:09Z")

</div>

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
