Fix issue with IDs reader on preloaded associations for composite primary keys

This commit is contained in:
Jay Ang 2024-06-04 21:08:29 +08:00
parent 3769f1eee6
commit 3e371c6dd6
3 changed files with 14 additions and 3 deletions

View File

@ -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`.

View File

@ -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

View File

@ -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