Skip to content

Commit 89bf564

Browse files
authored
Merge pull request rails#52359 from fatkodima/fix-find_or_initialize_by-for-cpk-associations
Fix `find_or_initialize_by` for finding by associations with composite primary keys
2 parents 55c4ade + ad021ae commit 89bf564

File tree

2 files changed

+17
-3
lines changed

2 files changed

+17
-3
lines changed

activerecord/lib/active_record/relation/predicate_builder/association_query_value.rb

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -57,9 +57,15 @@ def polymorphic_clause?
5757
end
5858

5959
def convert_to_id(value)
60-
return primary_key.map { |pk| value.public_send(pk) } if primary_key.is_a?(Array)
61-
62-
if value.respond_to?(primary_key)
60+
if primary_key.is_a?(Array)
61+
primary_key.map do |attribute|
62+
if attribute == "id"
63+
value.id_value
64+
else
65+
value.public_send(attribute)
66+
end
67+
end
68+
elsif value.respond_to?(primary_key)
6369
value.public_send(primary_key)
6470
else
6571
value

activerecord/test/cases/relations_test.rb

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1676,6 +1676,14 @@ def test_find_or_initialize_by_with_block
16761676
assert_equal bird, Bird.find_or_initialize_by(name: "bob", color: "blue")
16771677
end
16781678

1679+
def test_find_or_initialize_by_with_cpk_association
1680+
order1 = Cpk::Order.create!(id: [1, 1])
1681+
order2 = Cpk::Order.create!(id: [1, 2])
1682+
Cpk::Book.create!(id: [2, 1], order: order1)
1683+
book = Cpk::Book.find_or_initialize_by(order: order2)
1684+
assert_equal order2, book.order
1685+
end
1686+
16791687
def test_explicit_create_with
16801688
hens = Bird.where(name: "hen")
16811689
assert_equal "hen", hens.new.name

0 commit comments

Comments
 (0)