Search code examples
ruby-on-railspostgresqlarel

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


I'm trying to achieve the SQL with subquery below using Arel

students.classroom_id IN ( SELECT id FROM classrooms WHERE name IN ('foo', 'bar') )

I've tried the following combination

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

but when I execute .to_sql on that, it returns

students.classroom_id IN ( NULL NULL NULL NULL )

Any help will be appreciated.


Solution

  • I achieved my target output using the FF combination:

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