title: Rails: what is the best way to check if the record doesn't exist in the database?
body: <p>My method loads a list of countries(code, name) into the database, but before that it has to check, if the country data does not already exist. This works fine: </p>
  
  <pre><code> def self.load_countries
      get_countries.each do |country|
        code, name = country
        if find_by_code(code).nil?
          create({ 'name' =&gt; name, 'code' =&gt; code })
        end
      end
    end
  </code></pre>
  
  <p>However, as I am new to Ruby, I want to learn the best practises. So, in this code I am not sure about two things which might be (or might not be) optimised:</p>
  
  <ol>
  <li>find_by_attribute returns the "select * from table" statement. In this case, when I don't need any data from database - I just want to know if the record exists or not - selecting the entire row seems a little inefficient to me. Is there any better way solve this? For example, "select 1 from table where ..." using ActiveRecord?</li>
  <li><p>This question might be silly, but I want to be sure: when I start the loop with the get_countries.each, is it ok to use a method instead of a variable? Isn't the same method called each cycle (N times)? In other words, would this be anymore efficient:</p>
  
  <p>countries = get_countries</p>
  
  <p>countries.each do |country|</p></li>
  </ol>
  
  <p>Any comments on those few lines of code are welcome, since the fact it works doesn't necessarily mean that I am doing it the right way.</p>
  
  <p>Thank you.</p>