Skip to content

Commit fab8d07

Browse files
committed
Merge pull request rails#15444 from sgrif/sg-yaml-new-record
New records should remain new after yaml serialization
2 parents 87cc918 + e08494a commit fab8d07

File tree

4 files changed

+28
-2
lines changed

4 files changed

+28
-2
lines changed

activerecord/CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
* New records remain new after YAML serialization.
2+
3+
*Sean Griffin*
4+
15
* PostgreSQL support default values for enum types. Fixes #7814.
26

37
*Yves Senn*

activerecord/lib/active_record/core.rb

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -284,7 +284,7 @@ def init_with(coder)
284284

285285
init_internals
286286

287-
@new_record = false
287+
@new_record = coder['new_record']
288288

289289
self.class.define_attribute_methods
290290

@@ -354,6 +354,7 @@ def initialize_dup(other) # :nodoc:
354354
# coder # => {"attributes" => {"id" => nil, ... }}
355355
def encode_with(coder)
356356
coder['attributes'] = @raw_attributes
357+
coder['new_record'] = new_record?
357358
end
358359

359360
# Returns true if +comparison_object+ is the same exact object, or +comparison_object+

activerecord/lib/active_record/persistence.rb

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,11 @@ def create(attributes = nil, &block)
4949
def instantiate(attributes, column_types = {})
5050
klass = discriminate_class_for_record(attributes)
5151
column_types = klass.decorate_columns(column_types.dup)
52-
klass.allocate.init_with('attributes' => attributes, 'column_types' => column_types)
52+
klass.allocate.init_with(
53+
'attributes' => attributes,
54+
'column_types' => column_types,
55+
'new_record' => false,
56+
)
5357
end
5458

5559
private

activerecord/test/cases/yaml_serialization_test.rb

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,4 +52,21 @@ def test_cast_types_are_not_changed_on_round_trip
5252
assert_equal 123, topic.parent_id
5353
assert_equal 123, YAML.load(YAML.dump(topic)).parent_id
5454
end
55+
56+
def test_new_records_remain_new_after_round_trip
57+
topic = Topic.new
58+
59+
assert topic.new_record?, "Sanity check that new records are new"
60+
assert YAML.load(YAML.dump(topic)).new_record?, "Record should be new after deserialization"
61+
62+
topic.save!
63+
64+
assert_not topic.new_record?, "Saved records are not new"
65+
assert_not YAML.load(YAML.dump(topic)).new_record?, "Saved record should not be new after deserialization"
66+
67+
topic = Topic.select('title').last
68+
69+
assert_not topic.new_record?, "Loaded records without ID are not new"
70+
assert_not YAML.load(YAML.dump(topic)).new_record?, "Record should not be new after deserialization"
71+
end
5572
end

0 commit comments

Comments
 (0)