title: What is the most efficient way to determine if a record with a given property already exists in a Rails database?
body: <p>I am trying to avoid excess DB hits/queries in my rails site. Given an array of URLs, i need to know if a corresponding Website has already been created in my database or not, so that I can create it if needed.</p>
  
  <p>1) The first method selects all the urls  from the array and then queries this smaller set to determine if a given URL has been created</p>
  
  <pre><code>urls = ["https://www.google.com/", ... "https://stackoverflow.com"]
  my_sites = Website.where url: urls
  urls.each_with_index do |url, i|
    this_site = my_sites.find_by url: url
    if this_site == nil
      #do stuff
    end
  end
  </code></pre>
  
  <p>2) The second method selects each site from the record individually</p>
  
  <pre><code>urls = ["https://www.google.com/", ... "https://stackoverflow.com"]
  urls.each_with_index do |url, i|
    this_site = Website.find_by url: url
    if this_site == nil
      #do stuff
    end
  end
  </code></pre>
  
  <p>3) Another way? Neither of these seem too efficient, they are both opening a lot of DB connections I believe.</p>