Skip to content

Instantly share code, notes, and snippets.

@pdswan
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pdswan/3bb1a3104910bf646c47 to your computer and use it in GitHub Desktop.
Save pdswan/3bb1a3104910bf646c47 to your computer and use it in GitHub Desktop.
Union SQL Results in ActiveRecord 3 and ActiveRecord 4
[3] pry(main)> ActiveRecordScopeExtensions.union(User.where(name: "Bob"), User.where(name: "Alice")).to_sql
=> "SELECT \"users\".* FROM \"users\" INNER JOIN (( SELECT users.id FROM \"users\" WHERE \"users\".\"name\" = 'Bob' UNION SELECT users.id FROM \"users\" WHERE \"users\".\"name\" = 'Alice' )) as users_union_b96cf9af7d77c501088feac76f259ba6 ON users_union_b96cf9af7d77c501088feac76f259ba6.id = users.id"
[1] pry(main)> ActiveRecordScopeExtensions.union(User.where(name: "Bob"), User.where(name: "Alice")).to_sql
=> "SELECT \"users\".* FROM \"users\" INNER JOIN (( SELECT users.id FROM \"users\" WHERE \"users\".\"name\" = $1 UNION SELECT users.id FROM \"users\" WHERE \"users\".\"name\" = $2 )) as users_union_ae16bf60c34e782ed51dbd86bff218d5 ON users_union_ae16bf60c34e782ed51dbd86bff218d5.id = users.id"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment