How to join on subqueries using ARel?

前端 未结 3 1039
南笙
南笙 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:18

    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.

提交回复
热议问题