Forum: Ruby on Rails Idea to manipulate the ActiveRecord Relation

F455612694f0ccae4dffc89edf076359?d=identicon&s=25 unknown (Guest)
on 2013-09-12 08:14
(Received via mailing list)
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
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.