How to join on subqueries using ARel?

前端 未结 3 961
南笙
南笙 2021-02-04 14:22

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 w

3条回答
  •  别那么骄傲
    2021-02-04 15:02

    OK so my main problem was that you can't join a Arel::SelectManager ... BUT you can join a table aliasing. So to generate the request in my comment above:

    a = A.arel_table
    b = B.arel_table
    
    subquery = B.select(:a_id).where{c > 4}
    query = A.join(subquery.as('B')).on(b[:a_id].eq(a[:id])
    query.to_sql # SELECT A.* INNER JOIN (SELECT B.a_id FROM B WHERE B.c > 4) B ON A.id = B.a_id 
    

提交回复
热议问题