When building subqueries from associations, Active Record knows how to express an association as join constraints against its owner’s table (that’s how joins and where.associated work), but that logic isn’t exposed as a relation you can embed in another query. That makes correlated subqueries, a common and often efficient SQL pattern, awkward to write without either duplicating association logic or reaching into internals.
Given:
class Order < ApplicationRecord
belongs_to :user
scope :pending, -> { where(shipped_at: nil) }
end
class User < ApplicationRecord
has_many :orders
has_many :pending_orders, -> { pending }, class_name: "Order"
end
selecting each user’s pending order total today looks something like:
orders = Order.arel_table
users = User.arel_table
subquery = Order.pending
.where(orders[:user_id].eq(users[:id]))
.select(orders[:amount].sum)
User.select(users[Arel.star], Arel::Nodes::As.new(subquery.arel, Arel.sql("pending_orders_total")))
This works, but it repeats the foreign key and the scope rather than reusing the pending_orders association. More importantly, neither hand-written Arel nor SQL strings with to_sql can reuse Active Record’s handling of has_many :through, polymorphic, scoped, or composite-key associations, so every app or library that needs a correlated subquery has to reimplement that logic.
Proposal: a public method that returns an association’s relation, correlated to the outer query’s table, built from the same reflection and join constraints that joins uses:
User.correlated(:pending_orders)
# => Order relation: SELECT ... FROM orders WHERE orders.shipped_at IS NULL AND orders.user_id = users.id
This one primitive covers several patterns:
# Aggregate as a column
User.select("users.*", User.correlated(:pending_orders).select(Order.arel_table[:amount].sum).as(:pending_orders_total))
# Correlated EXISTS
User.where(User.correlated(:pending_orders).arel.exists)
# Ordering by an association aggregate
User.order(User.correlated(:orders).select(Order.arel_table[:created_at].maximum).arel.desc)
A smaller companion change would make the first example cleaner: letting a relation be used as an aliased scalar subquery in select (the .as(:pending_orders_total) above), instead of hand-building Arel::Nodes::As with a raw Arel.sql alias.
Prior art: Ransack already needs this capability and implements it privately. Ransack::Adapters::ActiveRecord::Context#build_correlated_subquery extracts an association’s join constraints from Active Record internals, uses AliasTracker and a hand-built Arel::SelectManager to construct the subquery, and branches on Rails version to keep up with internal changes. Reimplementing this outside Active Record is also error-prone: Ransack fixed a bug where its correlated subqueries dropped the association’s own join conditions (scopes, polymorphic types, custom keys) and silently returned wrong records (activerecord-hackery/ransack#1751). A public primitive would give libraries like Ransack a stable, correct API instead. I’ve also been using an aggregate helper built on the same idea in my own apps: Subqueries in Active Record
Would this be something core would consider? If there’s interest, I’m happy to work on a PR, and I’d welcome input on naming and API shape.
