Search code examples
ruby-on-railspostgresqlactiverecord

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


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


Solution

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

    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');