Skip to content

Instantly share code, notes, and snippets.

@StevenJL
Last active December 17, 2017 11:02
Show Gist options
  • Save StevenJL/84f9fb64a60ab00965d3bb61d61e33d8 to your computer and use it in GitHub Desktop.
Save StevenJL/84f9fb64a60ab00965d3bb61d61e33d8 to your computer and use it in GitHub Desktop.
# If we care to know a record exists, but actually don't
# need to do anything with the record...
if User.where(email: "[email protected]").present?
puts "There is a user with email address [email protected]"
else
puts "There is no user with email address [email protected]"
end
# then using `present?` is wasteful, as it selects all the column
# and loads the object into memory.
# SELECT * FROM users WHERE email` = '[email protected]';
# Instead, use `exists?`
if User.where(email: "[email protected]").exists?
puts "There is a user with email address [email protected]"
else
puts "There is no user with email address [email protected]"
end
# The advantage is the corresponding query limits only to 1 record
# and does not select any columns.
# SELECT 1 FROM users WHERE email` = '[email protected]' LIMIT 1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment