Rails ActiveRecord 中用于查询和子查询的 Arel 节点的正确组合

Proper combination of Arel nodes for Query with Subqueries in Rails ActiveRecord

我正在尝试使用 Arel

通过下面的子查询实现 SQL
students.classroom_id IN ( SELECT id FROM classrooms WHERE name IN ('foo', 'bar') )

我试过以下组合

Student.arel_table[:classroom_id].in(
  Classroom.where(
    Classroom.arel_table[:name].in(
      ['foo', 'bar']
    )
  ).select(:id)
)

但是当我在上面执行 .to_sql 时,它 returns

students.classroom_id IN ( NULL NULL NULL NULL )

任何帮助将不胜感激。

您确定没有 Arel 就无法实现这一目标吗?

Student.where(classroom: Classroom.where(name: ['foo', 'bar']))

我使用 FF 组合实现了我的目标输出:

subquery = Arel::Nodes::SqlLiteral.new Classroom.where(name: ['foo', 'bar'].select(:id).to_sql

Student.arel_table[:classroom_id].in(subquery)