Use a subquery with IDs only for find_by_any_email
This further improves performance of User.find_by_any_email and is roughly twice as fast as the previous UNION setup. Thanks again to @dlemstra for suggesting this.
This commit is contained in:
parent
bba46623c2
commit
a9df714764
|
@ -235,15 +235,13 @@ class User < ActiveRecord::Base
|
||||||
|
|
||||||
# Find a User by their primary email or any associated secondary email
|
# Find a User by their primary email or any associated secondary email
|
||||||
def find_by_any_email(email)
|
def find_by_any_email(email)
|
||||||
# Arel doesn't allow for chaining operations on union nodes, thus we have
|
sql = 'SELECT *
|
||||||
# to write this query by hand. See the following issue for more info:
|
FROM users
|
||||||
# https://github.com/rails/arel/issues/98.
|
WHERE id IN (
|
||||||
sql = '(SELECT * FROM users WHERE email = :email)
|
SELECT id FROM users WHERE email = :email
|
||||||
UNION
|
UNION
|
||||||
(SELECT users.*
|
SELECT emails.user_id FROM emails WHERE email = :email
|
||||||
FROM emails
|
)
|
||||||
INNER JOIN users ON users.id = emails.user_id
|
|
||||||
WHERE emails.email = :email)
|
|
||||||
LIMIT 1;'
|
LIMIT 1;'
|
||||||
|
|
||||||
User.find_by_sql([sql, { email: email }]).first
|
User.find_by_sql([sql, { email: email }]).first
|
||||||
|
|
Loading…
Reference in New Issue