Home > Enterprise >  Check if a value exists in a database and return the value if it does Rails
Check if a value exists in a database and return the value if it does Rails

Time:06-08

I am running Rails here with a User model that contains an :email_address column

I have an array - emails_to_check[email1,email2,email3] that i want to check if they exist in the User database.

I only want to return the values that DO exist in the database

CodePudding user response:

so i solved this using a rake task

task :find_users_in_array,[:emails_to_find] => :environment do |task, args|
emails = args[:emails_to_find].split

emails.each do |email|
  if User.find_by(email:email)
      puts "#{email}"
  end
end
end

I can pass in a list using rake:find_users_in_array[email1 email2 email3]

CodePudding user response:

Here's a one-liner for you. There may be more performant ways, but this is maybe the most straight-forward.

emails_to_check = ['email1', 'email2', 'email3']
User.where(email_address: emails_to_check).pluck(:email_address)

Here is the resulting SQL query:

SELECT `users`.`email_address` FROM `users` WHERE `users`.`email_address` IN ('email1', 'email2', 'email3');
  • Related