Fix n+1 query in settings migration (#24783)

lolsob-rspec
Eugen Rochko 2023-05-02 10:26:39 +02:00 committed by GitHub
parent 140e0f0bb7
commit d548faf693
1 changed files with 16 additions and 13 deletions

View File

@ -59,26 +59,29 @@ class MoveUserSettings < ActiveRecord::Migration[6.1]
end
def up
User.find_each do |user|
previous_settings = LegacySetting.where(thing_type: 'User', thing_id: user.id).index_by(&:var)
User.find_in_batches do |users|
previous_settings_for_batch = LegacySetting.where(thing_type: 'User', thing_id: users.map(&:id)).group_by(&:thing_id)
user_settings = {}
users.each do |user|
previous_settings = previous_settings_for_batch[user.id]&.index_by(&:var) || {}
user_settings = {}
MAPPING.each do |legacy_key, new_key|
value = previous_settings[legacy_key]&.value
MAPPING.each do |legacy_key, new_key|
value = previous_settings[legacy_key]&.value
next if value.blank?
next if value.blank?
if value.is_a?(Hash)
value.each do |nested_key, nested_value|
user_settings[MAPPING[legacy_key][nested_key.to_sym]] = nested_value
if value.is_a?(Hash)
value.each do |nested_key, nested_value|
user_settings[MAPPING[legacy_key][nested_key.to_sym]] = nested_value
end
else
user_settings[new_key] = value
end
else
user_settings[new_key] = value
end
end
user.update_column('settings', Oj.dump(user_settings)) # rubocop:disable Rails/SkipsModelValidations
user.update_column('settings', Oj.dump(user_settings)) # rubocop:disable Rails/SkipsModelValidations
end
end
end