From efb4880815dce50b6e6f41a969c96a8906c6f027 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. --- .../app/models/action_text/rich_text.rb | 2 +- actiontext/test/unit/model_test.rb | 22 +++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/actiontext/app/models/action_text/rich_text.rb b/actiontext/app/models/action_text/rich_text.rb index 5e021c2a60037..6c7613e2c3193 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.nil? ? [] : 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 571be07e672bd..3664a4e9b47ab 100644 --- a/actiontext/test/unit/model_test.rb +++ b/actiontext/test/unit/model_test.rb @@ -57,6 +57,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