How to join on subqueries using ARel?

Pierre Schambacher picture Pierre Schambacher · Apr 3, 2013 · Viewed 7.6k times · Source

I have a few massive SQL request involving join across various models in my rails application. A single request can involve 6 to 10 tables.

To run the request faster I want to use sub-queries in the joins (that way I can filter these tables before the join and reduce the columns to the ones I need). I'm trying to achieve this using ARel.

I thought I found the solution to my problem there: How to do joins on subqueries in AREL within Rails, but things must have changed because I get undefined method '[]' for Arel::SelectManager.

Does anybody have any idea how to achieve this (without using strings) ?

Answer

Ashwin Saval picture Ashwin Saval · Nov 6, 2013

Pierre, I thought a better solution could be the following (inspiration from this gist):

a = A.arel_table  
b = B.arel_table

subquery = b.project(b[:a_id].as('A_id')).where{c > 4}  
subquery = subquery.as('intm_table')  
query = A.join(subquery).on(subquery[:A_id].eq(a[:id]))

No particular reason for naming the alias as "intm_table", I just thought it would be less confusing.