Skip to content

Commit 0efc3e8

Browse files
authored
Merge pull request rails#53847 from seanpdoyle/action-text-embeds-before-validate
Change `ActionText::RichText#embeds` assignment to `before_validation`
2 parents 0694502 + 0eb9fa4 commit 0efc3e8

File tree

3 files changed

+23
-2
lines changed

3 files changed

+23
-2
lines changed

actiontext/CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,5 @@
1+
* Change `ActionText::RichText#embeds` assignment from `before_save` to `before_validation`
2+
3+
*Sean Doyle*
14

25
Please check [8-0-stable](https://github.com/rails/rails/blob/8-0-stable/actiontext/CHANGELOG.md) for previous changes.

actiontext/app/models/action_text/rich_text.rb

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,10 +48,13 @@ class RichText < Record
4848
##
4949
# :method: embeds
5050
#
51-
# Returns the `ActiveStorage::Blob`s of the embedded files.
51+
# Returns the `ActiveStorage::Attachment` records from the embedded files.
52+
#
53+
# Attached `ActiveStorage::Blob` records are extracted from the `body`
54+
# in a # [before_validation](/classes/ActiveModel/Validations/Callbacks/ClassMethods.html#method-i-before_validation) callback.
5255
has_many_attached :embeds
5356

54-
before_save do
57+
before_validation do
5558
self.embeds = body.attachables.grep(ActiveStorage::Blob).uniq if body.present?
5659
end
5760

actiontext/test/unit/model_test.rb

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,21 @@ class ActionText::ModelTest < ActiveSupport::TestCase
6161
end
6262
end
6363

64+
test "embed extraction occurs before validation" do
65+
blob = create_file_blob(filename: "racecar.jpg", content_type: "image/jpeg")
66+
content = ActionText::Content.new.append_attachables(blob)
67+
message = Message.build(subject: "Greetings", content: content)
68+
69+
assert_changes -> { message.content.embeds.empty? }, from: true, to: false do
70+
message.content.validate
71+
end
72+
73+
embeds = message.content.embeds
74+
assert_kind_of ActiveStorage::Attached::Many, embeds
75+
assert_kind_of ActiveStorage::Attachment, embeds.first
76+
assert_equal blob, embeds.first.blob
77+
end
78+
6479
test "saving content" do
6580
message = Message.create!(subject: "Greetings", content: "<h1>Hello world</h1>")
6681
assert_equal "Hello world", message.content.to_plain_text

0 commit comments

Comments
 (0)