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: 
Use `find_or_create_by`

```
get_countries.each do |country|
  code, name = country
  find_or_create_by_code_and_name(code, name)
end

```
1.) You don't necessarily need to select the whole row, and you could use the :select=> option to limit the columns you fetch, but this seems like a micro-optimization to me. I wouldn't worry about it. If the efficiency of this method bothers you that much, you'd be better off figuring out a way to avoid making an SQL query within a loop; for example, consider selecting all the existing countries before the loop, storing them in an array or hash, and using that to see if the country already exists. Then instead of dozens of trips to the database, you'd only make one (not counting those where you add new records). On the other hand, this doesn't sound like the kind of code you're going to be running lots of times (it sounds like a case of seeding a database table), so it might not matter much.

2.) No, the get\_countries method won't get called each iteration of the loop, only once before the #each starts; Assuming get\_countries returns an Array, #each is a method on the array.