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:
- 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?
-
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.
You can use the exists? function in ActiveRecord.
The get_countries function gets called only once. It returns an enumerable data type and then the each walks through each of them.