Skip to content

Commit

Permalink
Only serialize associations that were loaded
Browse files Browse the repository at this point in the history
Fix: rails#51807

`association_cached?` only means the Association object was
created, not that the records were loaded.

Co-Authored-By: benk-gc <bkyriakou@gocardless.com>
  • Loading branch information
byroot and benk-gc committed May 13, 2024
1 parent 8eae753 commit e0b66a3
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 2 deletions.
2 changes: 1 addition & 1 deletion activerecord/lib/active_record/marshalling.rb
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def _marshal_dump_7_1
payload = [attributes_for_database, new_record?]

cached_associations = self.class.reflect_on_all_associations.select do |reflection|
association_cached?(reflection.name)
association_cached?(reflection.name) && association(reflection.name).loaded?
end

unless cached_associations.empty?
Expand Down
2 changes: 1 addition & 1 deletion activerecord/lib/active_record/message_pack.rb
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ def build_entry(record)

def add_cached_associations(record, entry)
record.class.normalized_reflections.each_value do |reflection|
if record.association_cached?(reflection.name)
if record.association_cached?(reflection.name) && association(reflection.name).loaded?
entry << reflection.name << encode(record.association(reflection.name).target)
end
end
Expand Down
6 changes: 6 additions & 0 deletions activerecord/test/cases/marshal_serialization_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,10 @@ def test_rails_7_1_rountrip
assert_same topic, reply.topic
end

topic.association(:open_replies)
assert_equal true, topic.association_cached?(:open_replies)
refute_predicate topic.association(:open_replies), :loaded?

topic = Marshal.load(Marshal.dump(topic))

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

refute_predicate topic.association(:open_replies), :loaded?

assert_not_equal 0, topic.replies.size
topic.replies.each do |reply|
assert_same topic, reply.topic
Expand Down

0 comments on commit e0b66a3

Please sign in to comment.