From 3e371c6dd6077efa21aeea98cdd14b79822403a2 Mon Sep 17 00:00:00 2001 From: Jay Ang Date: Tue, 4 Jun 2024 21:08:29 +0800 Subject: [PATCH] Fix issue with IDs reader on preloaded associations for composite primary keys --- activerecord/CHANGELOG.md | 5 +++++ .../active_record/associations/collection_association.rb | 6 +++--- .../test/cases/associations/has_many_associations_test.rb | 6 ++++++ 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index 21275a8d504..c9b05e32210 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -1,3 +1,8 @@ +* Fix an issue where the IDs reader method did not return expected results + for preloaded associations in models using composite primary keys. + + *Jay Ang* + * Allow to configure `strict_loading_mode` globally or within a model. Defaults to `:all`, can be changed to `:n_plus_one_only`. diff --git a/activerecord/lib/active_record/associations/collection_association.rb b/activerecord/lib/active_record/associations/collection_association.rb index 65bfb3946a6..385d91dc5af 100644 --- a/activerecord/lib/active_record/associations/collection_association.rb +++ b/activerecord/lib/active_record/associations/collection_association.rb @@ -50,11 +50,11 @@ module ActiveRecord # Implements the ids reader method, e.g. foo.item_ids for Foo.has_many :items def ids_reader if loaded? - target.pluck(reflection.association_primary_key) + target.pluck(*reflection.association_primary_key) elsif !target.empty? - load_target.pluck(reflection.association_primary_key) + load_target.pluck(*reflection.association_primary_key) else - @association_ids ||= scope.pluck(reflection.association_primary_key) + @association_ids ||= scope.pluck(*reflection.association_primary_key) end end diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index 1c005fe8186..9b3aa8e4ca8 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -3234,6 +3234,12 @@ class HasManyAssociationsTest < ActiveRecord::TestCase MESSAGE end + def test_ids_reader_on_preloaded_association_with_composite_primary_key + great_author = cpk_authors(:cpk_great_author) + + assert_equal great_author.books.ids, Cpk::Author.preload(:books).find(great_author.id).book_ids + end + private def force_signal37_to_load_all_clients_of_firm companies(:first_firm).clients_of_firm.load_target