如何在Rails中的AREL中对子查询进行联接 [英] How to do joins on subqueries in AREL within Rails

查看:71
本文介绍了如何在Rails中的AREL中对子查询进行联接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的模型

class User
    has_many :logs


class Logs

通过外键logs.user_id以常规方式关联.我正在尝试使用Arel执行以下操作,根据Arel文档,它应该可以正常工作.

related in the usual way through the foreign key logs.user_id. I'm trying to do the following using Arel and according to the Arel doc it should work.

u_t = Arel::Table::new :users
l_t = Arel::Table::new :logs

counts = l_t.
    group(l_t[:user_id]).
    project(
        l_t[:user_id].as("user_id"),
        l_t[:user_id].count.as("count_all")
    )

l_t.joins(counts).on(l_t[:id].eq(counts[:user_id]))

这样做的时候我得到了错误

When I do that I get the error

TypeError: Cannot visit Arel::SelectManager

但是Arel的作者

However the author of Arel explicitly suggests that Arel can do this kind of thing.

请不要写关于如何使用原始sql,另一种Arel查询等实现相同查询的响应.这是我感兴趣的模式,而不是此查询的特定结果.

Please do not write responses on how I can achieve the same query with raw sql, another type of Arel query etc. It is the pattern I am interested in not the specific results of this query.

推荐答案

您可以使用join_sources从Arel :: SelectManager实例中检索Arel :: Nodes :: Join,并将其传递给联接

You can use join_sources to retrieve the Arel::Nodes::Join from the instance of Arel::SelectManager, and pass that to joins

使用您的示例:

l_t.joins(counts.join_sources).on(l_t[:id].eq(counts[:user_id]))

这篇关于如何在Rails中的AREL中对子查询进行联接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆