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

```
In Ruby on rails, we have four methods to check if a record exists in the database or not?

1. .present?

It is the most time-consuming method since it returns all records from the database.
2. .any? / .empty?

The above both have same performance efficiency since both of them finally fire a 'COUNT' query on the database. Hence this both are efficient when compared with .present?
3. .exist?

The last one is even more optimized, and it should be your first choice when checking the existence of a record. It uses the 'SELECT 1 ... LIMIT 1' approach.

Remember one thing when your ActiveRecord objects are already in memory (If you preloaded them) then do not use 'exist?' rather use 'any?', since 'exist?' always hit database in respect of whether the object is in-memory or not, whereas 'any? / empty?' fill not hit the database again if the records are already loaded into memory.

You can also refer to this article : [Check if record is exist in ROR](http://semaphoreci.com/blog/2017/03/14/faster-rails-how-to-check-if-a-record-exists.html)