Skip to content

Commit 568013e

Browse files
authored
Merge pull request rails#54314 from byroot/serialize-json-default
Fix `serialize coder: JSON, type: Hash` to wrap the coder in `ColumnSerializer`
2 parents 44988c1 + bd24ca3 commit 568013e

File tree

2 files changed

+10
-2
lines changed

2 files changed

+10
-2
lines changed

activerecord/lib/active_record/attribute_methods/serialization.rb

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -220,10 +220,12 @@ def build_column_serializer(attr_name, coder, type, yaml = nil)
220220
# to ensure special objects (e.g. Active Record models) are dumped correctly
221221
# using the #as_json hook.
222222

223+
if coder == ::JSON || coder == Coders::JSON
224+
coder = Coders::JSON.new
225+
end
226+
223227
if coder == ::YAML || coder == Coders::YAMLColumn
224228
Coders::YAMLColumn.new(attr_name, type, **(yaml || {}))
225-
elsif coder == ::JSON || coder == Coders::JSON
226-
Coders::JSON.new
227229
elsif coder.respond_to?(:new) && !coder.respond_to?(:load)
228230
coder.new(attr_name, type)
229231
elsif type && type != Object

activerecord/test/cases/serialized_attribute_test.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,12 @@ def test_json_read_db_null
149149
assert_nil t.content
150150
end
151151

152+
def test_json_type_hash_default_value
153+
Topic.serialize :content, coder: JSON, type: Hash
154+
t = Topic.new
155+
assert_equal({}, t.content)
156+
end
157+
152158
def test_json_symbolize_names_returns_symbolized_names
153159
Topic.serialize :content, coder: ActiveRecord::Coders::JSON.new(symbolize_names: true)
154160
my_post = posts(:welcome)

0 commit comments

Comments
 (0)