diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index 078d63f8f2..9da1304953 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -1,3 +1,7 @@ +* New records remain new after YAML serialization. + + *Sean Griffin* + * PostgreSQL support default values for enum types. Fixes #7814. *Yves Senn* diff --git a/activerecord/lib/active_record/core.rb b/activerecord/lib/active_record/core.rb index 205cae9b2a..88c1fc7e4c 100644 --- a/activerecord/lib/active_record/core.rb +++ b/activerecord/lib/active_record/core.rb @@ -284,7 +284,7 @@ module ActiveRecord init_internals - @new_record = false + @new_record = coder['new_record'] self.class.define_attribute_methods @@ -354,6 +354,7 @@ module ActiveRecord # coder # => {"attributes" => {"id" => nil, ... }} def encode_with(coder) coder['attributes'] = @raw_attributes + coder['new_record'] = new_record? end # Returns true if +comparison_object+ is the same exact object, or +comparison_object+ diff --git a/activerecord/lib/active_record/persistence.rb b/activerecord/lib/active_record/persistence.rb index 78ae05073a..2e3bcc0956 100644 --- a/activerecord/lib/active_record/persistence.rb +++ b/activerecord/lib/active_record/persistence.rb @@ -49,7 +49,11 @@ module ActiveRecord def instantiate(attributes, column_types = {}) klass = discriminate_class_for_record(attributes) column_types = klass.decorate_columns(column_types.dup) - klass.allocate.init_with('attributes' => attributes, 'column_types' => column_types) + klass.allocate.init_with( + 'attributes' => attributes, + 'column_types' => column_types, + 'new_record' => false, + ) end private diff --git a/activerecord/test/cases/yaml_serialization_test.rb b/activerecord/test/cases/yaml_serialization_test.rb index f7af9a35cd..d4f8ef5b4d 100644 --- a/activerecord/test/cases/yaml_serialization_test.rb +++ b/activerecord/test/cases/yaml_serialization_test.rb @@ -52,4 +52,21 @@ class YamlSerializationTest < ActiveRecord::TestCase assert_equal 123, topic.parent_id assert_equal 123, YAML.load(YAML.dump(topic)).parent_id end + + def test_new_records_remain_new_after_round_trip + topic = Topic.new + + assert topic.new_record?, "Sanity check that new records are new" + assert YAML.load(YAML.dump(topic)).new_record?, "Record should be new after deserialization" + + topic.save! + + assert_not topic.new_record?, "Saved records are not new" + assert_not YAML.load(YAML.dump(topic)).new_record?, "Saved record should not be new after deserialization" + + topic = Topic.select('title').last + + assert_not topic.new_record?, "Loaded records without ID are not new" + assert_not YAML.load(YAML.dump(topic)).new_record?, "Record should not be new after deserialization" + end end