FIX: Prevent saving empty string as a locale (#33481)

Post edits need to inform the backend if the locale is changed and is
sometimes set as `""`. This PR prevents the locale from being set to
`""` in the database, and includes a migration to purge the empty
strings.
This commit is contained in:
Natalie Tay
2025-07-04 17:20:42 +08:00
committed by GitHub
parent 4c7089f817
commit 75330efab0
6 changed files with 55 additions and 1 deletions
@@ -59,7 +59,7 @@ export default class PostLanguageSelector extends Component {
<dropdown.item>
<DButton
@label="post.localizations.post_language_selector.none"
@action={{fn this.selectPostLanguage ""}}
@action={{fn this.selectPostLanguage null}}
/>
</dropdown.item>
</DropdownMenu>
+2
View File
@@ -888,6 +888,8 @@ class Post < ActiveRecord::Base
self.baked_at = Time.zone.now
self.baked_version = BAKED_VERSION
end
self.locale = nil if locale.blank?
end
def advance_draft_sequence
+2
View File
@@ -415,6 +415,8 @@ class Topic < ActiveRecord::Base
inherit_auto_close_from_category
inherit_slow_mode_from_category
end
self.locale = nil if locale.blank?
end
after_save do
@@ -0,0 +1,28 @@
# frozen_string_literal: true
class NullifyBlankLocales < ActiveRecord::Migration[7.2]
def up
loop do
result = execute(<<~SQL)
UPDATE topics
SET locale = NULL
WHERE id IN (SELECT id FROM topics WHERE locale = '' LIMIT 5000)
SQL
break if result.cmd_tuples == 0
end
loop do
result = execute(<<~SQL)
UPDATE posts
SET locale = NULL
WHERE id IN (SELECT id FROM posts WHERE locale = '' LIMIT 5000)
SQL
break if result.cmd_tuples == 0
end
end
def down
raise ActiveRecord::IrreversibleMigration
end
end
+11
View File
@@ -2409,4 +2409,15 @@ RSpec.describe Post do
expect(post.in_user_locale?).to eq(false)
end
end
describe "#before_save" do
it "replaces empty locales with nil" do
post = Fabricate(:post, locale: "en")
post.locale = ""
post.save!
expect(post.reload.locale).to eq(nil)
end
end
end
+11
View File
@@ -3332,6 +3332,17 @@ describe Topic do
end
end
describe "#before_save" do
it "replaces empty locales with nil" do
topic = Fabricate(:topic, locale: "en")
topic.locale = ""
topic.save!
expect(topic.reload.locale).to eq(nil)
end
end
describe "#after_update" do
fab!(:topic) { Fabricate(:topic, user: user) }
fab!(:category) { Fabricate(:category_with_definition, read_restricted: true) }