Rails: what's the best way to check if there is a record in the database?

My method loads the list of countries (code, name) into the database, but before that it should check if the country data does not already exist. This works great:

 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, since I'm new to Ruby, I want to learn best practices. So, in this code, I'm not sure of two things that can be optimized (or cannot be):

  • find_by_attribute returns the select * from table operator. In this case, when I don't need any data from the database, I just want to know if the record exists or not. Selecting an entire row is a little inefficient for me. Is there a better way to solve this problem? For example, "select 1 from the table where ..." using ActiveRecord?
  • , : get_countries.each, ? (N )? , :

    countries = get_countries

    countries.each do | country |

, , , , .

.

+3
6

? 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

get_countries . , .

+10

find_or_create_by

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

1) ( , Rails 3)

validates :code, :uniqueness => true

db/seeds.rb . IMHO 'load_countries' ( ).

+1

ActiveRecord, :

class Country < ActiveRecord::Base
  validates_uniqueness_of :code
  validates_uniqueness_of :name
end
0

1.) , : select = > , , , -. . , , SQL- ; , , , , . ( , ). , , ( ), .

2.) No, the get_countries method will not be called every iteration of the loop, only once before running #each; Assuming get_countries returns an Array, #each is an array method.

0
source

Source: https://habr.com/ru/post/1776345/


All Articles