Subqueries in activerecord

gucki picture gucki · Mar 30, 2011 · Viewed 55.2k times · Source

With SQL I can easily do sub-queries like this

User.where(:id => Account.where(..).select(:user_id))

This produces:

SELECT * FROM users WHERE id IN (SELECT user_id FROM accounts WHERE ..)

How can I do this using rails' 3 activerecord/ arel/ meta_where?

I do need/ want real subqueries, no ruby workarounds (using several queries).

Answer

Christopher Lindblom picture Christopher Lindblom · May 31, 2012

Rails now does this by default :)

Message.where(user_id: Profile.select("user_id").where(gender: 'm'))

will produce the following SQL

SELECT "messages".* FROM "messages" WHERE "messages"."user_id" IN (SELECT user_id FROM "profiles" WHERE "profiles"."gender" = 'm')

(the version number that "now" refers to is most likely 3.2)