ernie/squeel — Issue #101: How to do this with SQUEEL
Author: bradphelan
Created: 2012-01-24 10:12:48+00:00
State: open

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")
).as "foo"

users = u_t.
join(counts).
on(u_t[:id].
eq(counts[:user_id])).
project("*").project(counts[:count_all])

puts users.to_sql

generates the SQL

SELECT *, foo."count_all" FROM "users"
INNER JOIN (
SELECT "logs"."user_id" AS user_id, COUNT("logs"."user_id") AS count_all
FROM "logs"
GROUP BY "logs"."user_id"
) foo
ON "users"."id" = foo."user_id"