Skip to content

Commit 20d8750

Browse files
authored
Merge pull request rails#46126 from alexandreruban/fix-as-json-action-text-attachables
Fix ActionText::Attachable#as_json
2 parents bf560f6 + 6c2132b commit 20d8750

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

actiontext/lib/action_text/attachable.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ def previewable_attachable?
6464
end
6565

6666
def as_json(*)
67-
super.merge(attachable_sgid: attachable_sgid)
67+
super.merge("attachable_sgid" => persisted? ? attachable_sgid : nil)
6868
end
6969

7070
def to_trix_content_attachment_partial_path
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# frozen_string_literal: true
2+
3+
require "test_helper"
4+
5+
class ActionText::AttachableTest < ActiveSupport::TestCase
6+
test "as_json is a hash when the attachable is persisted" do
7+
freeze_time do
8+
attachable = ActiveStorage::Blob.create_after_unfurling!(io: StringIO.new("test"), filename: "test.txt", key: 123)
9+
attributes = {
10+
id: attachable.id,
11+
key: "123",
12+
filename: "test.txt",
13+
content_type: "text/plain",
14+
metadata: { identified: true },
15+
service_name: "test",
16+
byte_size: 4,
17+
checksum: "CY9rzUYh03PK3k6DJie09g==",
18+
created_at: Time.zone.now.as_json,
19+
attachable_sgid: attachable.attachable_sgid
20+
}.deep_stringify_keys
21+
22+
assert_equal attributes, attachable.as_json
23+
end
24+
end
25+
26+
test "as_json is a hash when the attachable is a new record" do
27+
attachable = ActiveStorage::Blob.build_after_unfurling(io: StringIO.new("test"), filename: "test.txt", key: 123)
28+
attributes = {
29+
id: nil,
30+
key: "123",
31+
filename: "test.txt",
32+
content_type: "text/plain",
33+
metadata: { identified: true },
34+
service_name: "test",
35+
byte_size: 4,
36+
checksum: "CY9rzUYh03PK3k6DJie09g==",
37+
created_at: nil,
38+
attachable_sgid: nil
39+
}.deep_stringify_keys
40+
41+
assert_equal attributes, attachable.as_json
42+
end
43+
end

0 commit comments

Comments
 (0)