Only serialize associations that were loaded

Fix: https://github.com/rails/rails/issues/51807

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

Co-Authored-By: benk-gc <bkyriakou@gocardless.com>
This commit is contained in:
Jean Boussier 2024-05-14 08:26:04 +09:00
parent 8eae75379c
commit db4dba78c9
3 changed files with 8 additions and 2 deletions

View File

@ -25,7 +25,7 @@ module ActiveRecord
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?

View File

@ -80,7 +80,7 @@ module ActiveRecord
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) && record.association(reflection.name).loaded?
entry << reflection.name << encode(record.association(reflection.name).target)
end
end

View File

@ -78,6 +78,10 @@ class MarshalSerializationTest < ActiveRecord::TestCase
assert_same topic, reply.topic
end
topic.association(:open_replies)
assert_equal true, topic.association_cached?(:open_replies)
assert_not_predicate topic.association(:open_replies), :loaded?
topic = Marshal.load(Marshal.dump(topic))
assert_not_predicate topic, :new_record?
@ -86,6 +90,8 @@ class MarshalSerializationTest < ActiveRecord::TestCase
assert_equal "Have a nice day", topic.content
assert_predicate topic.association(:replies), :loaded?
assert_not_predicate topic.association(:open_replies), :loaded?
assert_not_equal 0, topic.replies.size
topic.replies.each do |reply|
assert_same topic, reply.topic