From 4a4f7a7b2bcb6218f49104f705e71a48e9e53bec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A9=20Dupuis?= Date: Sun, 10 Mar 2024 14:58:29 -0700 Subject: [PATCH] Empty embeds when RichText is set to an empty content Fix #51269 Action Text supports saving a RichText model with empty content. Passing _almost_ empty content (such as a space) flushes the embeds, but passing truly empty content does not. This defies expectations. This change ensures that the embeds are flushed when empty content is passed. --- actiontext/CHANGELOG.md | 4 ++++ .../app/models/action_text/rich_text.rb | 2 +- actiontext/test/unit/model_test.rb | 22 +++++++++++++++++++ 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/actiontext/CHANGELOG.md b/actiontext/CHANGELOG.md index 281ee186e32d..bfd9b42d235f 100644 --- a/actiontext/CHANGELOG.md +++ b/actiontext/CHANGELOG.md @@ -1,3 +1,7 @@ +* Clear embeds when emptying an `ActionText::RichText`. + + *JoƩ Dupuis* + ## Rails 8.0.0.beta1 (September 26, 2024) ## * Dispatch direct-upload events on attachment uploads diff --git a/actiontext/app/models/action_text/rich_text.rb b/actiontext/app/models/action_text/rich_text.rb index 5e021c2a6003..3d3a95c7b706 100644 --- a/actiontext/app/models/action_text/rich_text.rb +++ b/actiontext/app/models/action_text/rich_text.rb @@ -52,7 +52,7 @@ class RichText < Record has_many_attached :embeds before_save do - self.embeds = body.attachables.grep(ActiveStorage::Blob).uniq if body.present? + self.embeds = body.blank? ? [] : body.attachables.grep(ActiveStorage::Blob).uniq end # Returns a plain-text version of the markup contained by the `body` attribute, diff --git a/actiontext/test/unit/model_test.rb b/actiontext/test/unit/model_test.rb index 426d1176f13b..4a4ff7ad9137 100644 --- a/actiontext/test/unit/model_test.rb +++ b/actiontext/test/unit/model_test.rb @@ -61,6 +61,28 @@ class ActionText::ModelTest < ActiveSupport::TestCase end end + test "saving empty content empties the embeds" do + blob = create_file_blob(filename: "racecar.jpg", content_type: "image/jpeg") + message = Message.create!(subject: "Greetings", content: ActionText::Content.new("Hello world").append_attachables(blob)) + assert message.content.embeds.sole + + message.content = "" + message.save + + assert_empty message.content.embeds + end + + test "saving nil content empties the embeds" do + blob = create_file_blob(filename: "racecar.jpg", content_type: "image/jpeg") + message = Message.create!(subject: "Greetings", content: ActionText::Content.new("Hello world").append_attachables(blob)) + assert message.content.embeds.sole + + message.content = nil + message.save + + assert_empty message.content.embeds + end + test "saving content" do message = Message.create!(subject: "Greetings", content: "

Hello world

") assert_equal "Hello world", message.content.to_plain_text