Re: How complex a query can ActiveRecord handle before it''s better using Raw SQL or a View???

Frederick Cheung
Fri, 19 Dec 2008 01:48:38 -0000

On 19 Dec 2008, at 01:25, Greg Hauptmann wrote:

> Hi,
>
> How complex a query can ActiveRecord handle before it''s better
using
> Raw SQL or a View???
>
Depends what you mean by handle. If you mean "will ruby run out of
steam" then that''s purely a function of the result set,
instantiating
1 million ActiveRecord objects is probably not a good idea.
If you mean handle as in get ActiveRecord to generate it without
writing any sql yourself then I don''t believe there''s a hard
and fast
rule or anything like that.
You might be able to get away with

Transaction.find :all, :joins => [:category, {:allocation => :person}],
		       :conditions => {''people.id'' => bob,
''categories.tax_id'' =>
1234, ''transactions.created_at'' => (1.week.ago ..
Time.now)}

or maybe the relations you need to express don''t quite map to those
things activerecord makes easy. It''s a case by case thing, much as
I''d
far write the above than write the equivalent sql, I wouldn''t waste
time trying to force activerecord through hoops when it was clear that
it wasn''t time well spent.

Fred
> I need to calculate for example taxable income via a query going
> across 5 tables.  Some like this: Find all transaction records
> (transactions table), for which they are allocated (via allocation
> table) to person X (person table), for transaction dates within
> date1 & date2, for which the category (categories table) associated
> with transaction, has a tax_id (from tax_codes table) of XYZ.  I
> will need to reuse this type of query as I build a report of various
> tax categories.
>
> Question - What would Rails best practice way for the above?
>
> [I''m thinking best to create a flat view of this and use this to
> then query against]
>
> Thanks