Proposal: public API for correlating an association to the outer query

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.

Why don’t you just use a GROUP BY?

User.left_joins(:pending_orders).group(:id).select('users.*', 'SUM(orders.amount)')

Why don’t you just use a GROUP BY?

That works for a single aggregate, but it breaks down for multiple aggregates. Say you want both pending and shipped totals:

User.left_joins(:pending_orders, :shipped_orders)
  .group(:id)
  .select("users.*", "SUM(orders.amount)", "SUM(shipped_orders_users.amount)")

This runs into a fan-out problem: the two joins multiply rows (pending × shipped), so each sum is inflated by the other’s row count. And the second join gets a Rails-generated table alias you have to know and hard-code in the SQL string. The usual workaround is a single join with SUM(CASE WHEN ...) expressions, but that undesirably duplicates the scopes’ logic in SQL. Correlated subqueries avoid both problems: each aggregate is computed independently, and it reuses the already-defined association.

I suppose in that case I’d use windowing functions with FILTER, which would also mean no need for the scopes:

User.left_joins(:orders).group(:id).select('users.*',
  'SUM(orders.amount) FILTER(WHERE shipped_date IS NULL) AS pending_order_total',
  'SUM(orders.amount) FILTER(WHERE shipped_date IS NOT NULL) AS shipped_order_total')

To me having correlated subqueries managed by ActiveRecord feels quite a bit more involved. (Although using FILTER is only supported in Postgres, Sqlite, Oracle, and MSSQL.)

FILTER works well for simple conditions, but if I still need the scopes elsewhere, this approach duplicates their logic in SQL strings. My example uses a very simple scope; real scopes may be more complex, and they can change over time.

Once the same logic lives in both a scope and a FILTER clause (or any other raw SQL), the two can silently drift apart: it’s easy to update a scope and miss the raw SQL that’s supposed to mirror it.

One reason I prefer window functions where possible is because everything is evaluated with one scan operation. So with every additional function you need then having all those multiple window functions can end up being multiple times faster than using subqueries:

There are more complex examples though that window functions can’t address. In that light perhaps we can create a more involved example and see what kind of options would exist. Some kind of “reference case”.

Incidentally, I have solved the “what the fuck did AREL name the aliases this time?” question with my gem The Brick. In your example where there’s two scopes and then both are JOINed at once, here’s how to determine the alias names:

4.0.7 :006 > relation = User.joins(:pending_orders, :shipped_orders)
4.0.7 :007 > relation.brick_links
 => {"" => "users",
     "pending_orders" => "orders",
     "shipped_orders" => "shipped_orders_users"}

Docs for this feature are found here.

1 Like