From b1495884ebcc74291d2bd8972de61a31e390eeec Mon Sep 17 00:00:00 2001 From: Alan Guo Xiang Tan Date: Thu, 7 Mar 2024 16:38:11 +0800 Subject: [PATCH] PERF: Avoid saving `ThemeSetting` twice when creating new db override (#26076) Why this change? When creating a new theme setting that does not have a corresponding row in the `theme_settings` table, we end up writing to the database twice because `ActiveRecord::Base#save!` is called once before the `value` or `json_value` column is updated again with another database query with another call to `ActiveRecord::Base#save!`. What does this change do? Adds the column to be updated to argument for the `ActiveRecord::Base#create!` method call so that we only have one write query to the database. --- lib/theme_settings_manager.rb | 18 +++++++++++------- lib/theme_settings_manager/objects.rb | 5 +---- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/lib/theme_settings_manager.rb b/lib/theme_settings_manager.rb index 3ee7761d03e..300c026ff99 100644 --- a/lib/theme_settings_manager.rb +++ b/lib/theme_settings_manager.rb @@ -53,10 +53,10 @@ class ThemeSettingsManager def value=(new_value) ensure_is_valid_value!(new_value) + value = new_value.to_s + + record = has_record? ? update_record!(value:) : create_record!(value:) - record = has_record? ? db_record : create_record! - record.value = new_value.to_s - record.save! record.value end @@ -68,16 +68,20 @@ class ThemeSettingsManager end end - def has_record? - db_record.present? + def update_record!(args) + db_record.tap { |instance| instance.update!(args) } end - def create_record! - record = ThemeSetting.new(name: @name, data_type: type, theme: @theme) + def create_record!(args) + record = ThemeSetting.new(name: @name, data_type: type, theme: @theme, **args) record.save! record end + def has_record? + db_record.present? + end + def ensure_is_valid_value!(new_value) return if new_value.nil? diff --git a/lib/theme_settings_manager/objects.rb b/lib/theme_settings_manager/objects.rb index 09da18bde79..5c53f28c19e 100644 --- a/lib/theme_settings_manager/objects.rb +++ b/lib/theme_settings_manager/objects.rb @@ -7,10 +7,7 @@ class ThemeSettingsManager::Objects < ThemeSettingsManager def value=(objects) ensure_is_valid_value!(objects) - - record = has_record? ? db_record : create_record! - record.json_value = objects - record.save! + record = has_record? ? update_record!(json_value: objects) : create_record!(json_value: objects) theme.reload record.json_value end