如何加入使用阿雷尔子查询? [英] How to join on subqueries using ARel?
问题描述
我有涉及跨各种型号加入我的Rails应用程序的几个大规模的SQL请求。 单个请求可以包括6到10个表。
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.
我想我找到了解决我的问题有:<一href="http://stackoverflow.com/questions/7528750/how-to-do-joins-on-subqueries-in-arel-within-rails">How做加盟的内滑轨子查询AREL 但事情必须改变了,因为我得到了一个未定义的方法`[]'为阿雷尔:: SelectManager。
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) ?
推荐答案
皮埃尔,我想到了一个更好的解决方案可能是由以下(灵感的这个要点):
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]))
命名别名为intm_table没有特别的原因,我只是认为这将是减少混乱。
No particular reason for naming the alias as "intm_table", I just thought it would be less confusing.
这篇关于如何加入使用阿雷尔子查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!