Skip to content

Commit db4dba7

Browse files
byrootbenk-gc
andcommitted
Only serialize associations that were loaded
Fix: rails#51807 `association_cached?` only means the Association object was created, not that the records were loaded. Co-Authored-By: benk-gc <[email protected]>
1 parent 8eae753 commit db4dba7

File tree

3 files changed

+8
-2
lines changed

3 files changed

+8
-2
lines changed

activerecord/lib/active_record/marshalling.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ def _marshal_dump_7_1
2525
payload = [attributes_for_database, new_record?]
2626

2727
cached_associations = self.class.reflect_on_all_associations.select do |reflection|
28-
association_cached?(reflection.name)
28+
association_cached?(reflection.name) && association(reflection.name).loaded?
2929
end
3030

3131
unless cached_associations.empty?

activerecord/lib/active_record/message_pack.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ def build_entry(record)
8080

8181
def add_cached_associations(record, entry)
8282
record.class.normalized_reflections.each_value do |reflection|
83-
if record.association_cached?(reflection.name)
83+
if record.association_cached?(reflection.name) && record.association(reflection.name).loaded?
8484
entry << reflection.name << encode(record.association(reflection.name).target)
8585
end
8686
end

activerecord/test/cases/marshal_serialization_test.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,10 @@ def test_rails_7_1_rountrip
7878
assert_same topic, reply.topic
7979
end
8080

81+
topic.association(:open_replies)
82+
assert_equal true, topic.association_cached?(:open_replies)
83+
assert_not_predicate topic.association(:open_replies), :loaded?
84+
8185
topic = Marshal.load(Marshal.dump(topic))
8286

8387
assert_not_predicate topic, :new_record?
@@ -86,6 +90,8 @@ def test_rails_7_1_rountrip
8690
assert_equal "Have a nice day", topic.content
8791
assert_predicate topic.association(:replies), :loaded?
8892

93+
assert_not_predicate topic.association(:open_replies), :loaded?
94+
8995
assert_not_equal 0, topic.replies.size
9096
topic.replies.each do |reply|
9197
assert_same topic, reply.topic

0 commit comments

Comments
 (0)