Commit 44be82dd authored by Yorick Peterse's avatar Yorick Peterse

Refactor User.find_by_any_email

By using SQL::Union we can return a proper ActiveRecord::Relation,
making it possible to select the columns we're interested in (instead of
all of them).
parent 673b6be1
...@@ -269,16 +269,16 @@ class User < ActiveRecord::Base ...@@ -269,16 +269,16 @@ 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)
sql = 'SELECT * by_any_email(email).take
FROM users end
WHERE id IN (
SELECT id FROM users WHERE email = :email # Returns a relation containing all the users for the given Email address
UNION def by_any_email(email)
SELECT emails.user_id FROM emails WHERE email = :email users = where(email: email)
) emails = joins(:emails).where(emails: { email: email })
LIMIT 1;' union = Gitlab::SQL::Union.new([users, emails])
User.find_by_sql([sql, { email: email }]).first from("(#{union.to_sql}) #{table_name}")
end end
def filter(filter_name) def filter(filter_name)
......
...@@ -841,6 +841,19 @@ describe User do ...@@ -841,6 +841,19 @@ describe User do
end end
end end
describe '.by_any_email' do
it 'returns an ActiveRecord::Relation' do
expect(described_class.by_any_email('foo@example.com'))
.to be_a_kind_of(ActiveRecord::Relation)
end
it 'returns a relation of users' do
user = create(:user)
expect(described_class.by_any_email(user.email)).to eq([user])
end
end
describe '.search' do describe '.search' do
let!(:user) { create(:user, name: 'user', username: 'usern', email: 'email@gmail.com') } let!(:user) { create(:user, name: 'user', username: 'usern', email: 'email@gmail.com') }
let!(:user2) { create(:user, name: 'user name', username: 'username', email: 'someemail@gmail.com') } let!(:user2) { create(:user, name: 'user name', username: 'username', email: 'someemail@gmail.com') }
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment