Skip to content

Commit 64eecd9

Browse files
committed
Fix include? on composite key relations
1 parent 51f8126 commit 64eecd9

File tree

2 files changed

+16
-7
lines changed

2 files changed

+16
-7
lines changed

activerecord/lib/active_record/associations/collection_association.rb

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -256,14 +256,16 @@ def replace(other_array)
256256
end
257257

258258
def include?(record)
259-
if record.is_a?(reflection.klass)
260-
if record.new_record?
261-
include_in_memory?(record)
262-
else
263-
loaded? ? target.include?(record) : scope.exists?(record.id)
264-
end
259+
klass = reflection.klass
260+
return false unless record.is_a?(klass)
261+
262+
if record.new_record?
263+
include_in_memory?(record)
264+
elsif loaded?
265+
target.include?(record)
265266
else
266-
false
267+
record_id = klass.composite_primary_key? ? klass.primary_key.zip(record.id).to_h : record.id
268+
scope.exists?(record_id)
267269
end
268270
end
269271

activerecord/test/cases/associations/has_many_associations_test.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2029,6 +2029,13 @@ def test_included_in_collection
20292029
assert_equal true, companies(:first_firm).clients.include?(Client.find(2))
20302030
end
20312031

2032+
def test_included_in_collection_for_composite_keys
2033+
great_author = cpk_authors(:cpk_great_author)
2034+
book = great_author.books.first
2035+
2036+
assert great_author.books.include?(book)
2037+
end
2038+
20322039
def test_included_in_collection_for_new_records
20332040
client = Client.create(name: "Persisted")
20342041
assert_nil client.client_of

0 commit comments

Comments
 (0)