Skip to content

Commit

Permalink
Empty embeds when RichText is set to an empty content
Browse files Browse the repository at this point in the history
Fix rails#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.
  • Loading branch information
JoeDupuis committed Mar 12, 2024
1 parent bf96dcf commit efb4880
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
2 changes: 1 addition & 1 deletion actiontext/app/models/action_text/rich_text.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
22 changes: 22 additions & 0 deletions actiontext/test/unit/model_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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: "<h1>Hello world</h1>")
assert_equal "Hello world", message.content.to_plain_text
Expand Down

0 comments on commit efb4880

Please sign in to comment.