In my Rails4.2 app a :user belongs_to :country and a :country has_many :users
In a migration I've the following script:
default_country = Country.find_or_create_by(code: 'it', name: 'Italy')
User.find_each do |user|
country = user.country || default_country
params_to_update = {}
params_to_update[:country_id] = country.id unless user.country_id
# get list of user's country areas ids
user_country_areas_ids = Area.by_country(country).pluck(:id)
# update user's area if current area does not belong to user's country
params_to_update[:area_id] = country.default_area.id unless user_country_areas_ids.include?(user.area_id)
# update user's locale with user country's default locale
params_to_update[:locale] = country.domain.default_locale
user.update_columns(params_to_update)
end
I see by the log that every time the variable country is used, a query it's perfomed, like:
[2018-01-03T14:04:05.663035 #17647] DEBUG -- :
Country Load (0.3ms) SELECT "countries".*
FROM "countries"
WHERE "countries"."id" = 1
LIMIT 1 [["id", 1]]
Every query takes around 0.3ms, which on my large DB sum up to a fairly big amount of time; is there a way to save the country object in memory to avoid hitting the DB every time it's called?