From bd24ca32cef5c82e50a74640756c07e20583d481 Mon Sep 17 00:00:00 2001 From: Jean Boussier Date: Tue, 21 Jan 2025 14:30:11 +0100 Subject: [PATCH] Fix `serialize coder: JSON, type: Hash` to wrap the coder in `ColumnSerializer` Fix: https://github.com/rails/rails/issues/54311 --- .../lib/active_record/attribute_methods/serialization.rb | 6 ++++-- activerecord/test/cases/serialized_attribute_test.rb | 6 ++++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/activerecord/lib/active_record/attribute_methods/serialization.rb b/activerecord/lib/active_record/attribute_methods/serialization.rb index a9f4e13cc26b..55c22203f44c 100644 --- a/activerecord/lib/active_record/attribute_methods/serialization.rb +++ b/activerecord/lib/active_record/attribute_methods/serialization.rb @@ -220,10 +220,12 @@ def build_column_serializer(attr_name, coder, type, yaml = nil) # to ensure special objects (e.g. Active Record models) are dumped correctly # using the #as_json hook. + if coder == ::JSON || coder == Coders::JSON + coder = Coders::JSON.new + end + if coder == ::YAML || coder == Coders::YAMLColumn Coders::YAMLColumn.new(attr_name, type, **(yaml || {})) - elsif coder == ::JSON || coder == Coders::JSON - Coders::JSON.new elsif coder.respond_to?(:new) && !coder.respond_to?(:load) coder.new(attr_name, type) elsif type && type != Object diff --git a/activerecord/test/cases/serialized_attribute_test.rb b/activerecord/test/cases/serialized_attribute_test.rb index 8df3604f9abb..ac08566f732a 100644 --- a/activerecord/test/cases/serialized_attribute_test.rb +++ b/activerecord/test/cases/serialized_attribute_test.rb @@ -149,6 +149,12 @@ def test_json_read_db_null assert_nil t.content end + def test_json_type_hash_default_value + Topic.serialize :content, coder: JSON, type: Hash + t = Topic.new + assert_equal({}, t.content) + end + def test_json_symbolize_names_returns_symbolized_names Topic.serialize :content, coder: ActiveRecord::Coders::JSON.new(symbolize_names: true) my_post = posts(:welcome)