From 6007e584d824225e51f47ba0684d48ea3eb8f518 Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Thu, 12 May 2016 09:06:29 -0400 Subject: Fix false positive mutation detection when JSON is used with serialize When looking for mutation, we compare the serialized version of the value to the before_type_cast form. `Type::Serialized` was breaking this contract by passing the already serialized attribute to the subtype's mutation detection. This never manifested previously, as all mutable subtypes either didn't do anything in their `serialize` method, or had a way to detect double serialization (e.g. `is_a?(String)`). However, now that JSON types can handle string primitives, we need to avoid double serialization. Fixes #24993. --- activerecord/lib/active_record/type/serialized.rb | 8 +++++- .../test/cases/serialized_attribute_test.rb | 33 ++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) (limited to 'activerecord') diff --git a/activerecord/lib/active_record/type/serialized.rb b/activerecord/lib/active_record/type/serialized.rb index 4ff0740cfb..a3a5241780 100644 --- a/activerecord/lib/active_record/type/serialized.rb +++ b/activerecord/lib/active_record/type/serialized.rb @@ -32,7 +32,7 @@ module ActiveRecord def changed_in_place?(raw_old_value, value) return false if value.nil? - raw_new_value = serialize(value) + raw_new_value = encoded(value) raw_old_value.nil? != raw_new_value.nil? || subtype.changed_in_place?(raw_old_value, raw_new_value) end @@ -52,6 +52,12 @@ module ActiveRecord def default_value?(value) value == coder.load(nil) end + + def encoded(value) + unless default_value?(value) + coder.dump(value) + end + end end end end diff --git a/activerecord/test/cases/serialized_attribute_test.rb b/activerecord/test/cases/serialized_attribute_test.rb index 6056156698..846be857d0 100644 --- a/activerecord/test/cases/serialized_attribute_test.rb +++ b/activerecord/test/cases/serialized_attribute_test.rb @@ -295,4 +295,37 @@ class SerializedAttributeTest < ActiveRecord::TestCase topic.update_attribute :content, nil assert_equal [topic], Topic.where(content: nil) end + + def test_mutation_detection_does_not_double_serialize + coder = Object.new + def coder.dump(value) + return if value.nil? + value + " encoded" + end + def coder.load(value) + return if value.nil? + value.gsub(" encoded", "") + end + type = Class.new(ActiveModel::Type::Value) do + include ActiveModel::Type::Helpers::Mutable + + def serialize(value) + return if value.nil? + value + " serialized" + end + + def deserialize(value) + return if value.nil? + value.gsub(" serialized", "") + end + end.new + model = Class.new(Topic) do + attribute :foo, type + serialize :foo, coder + end + + topic = model.create!(foo: "bar") + topic.foo + refute topic.changed? + end end -- cgit v1.2.3