Question: 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: 

```
 def self.load_countries
    get_countries.each do |country|
      code, name = country
      if find_by_code(code).nil?
        create({ 'name' => name, 'code' => code })
      end
    end
  end

```

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:

1. 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?
2. 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:

countries = get\_countries

countries.each do |country|

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.

Thank you.

Answer: 
You can use the exists? function in ActiveRecord.

```
def self.load_countries
  get_countries.each do |country|
    code, name = country
    unless exists?(:code => code)
      create({ :name => name, :code => code })
    end
  end
end

```

The get\_countries function gets called only once. It returns an enumerable data type and then the each walks through each of them.
Maybe you have to use UNIQUE for codes in your database model?

I mean this
<http://ar.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html#M000086>