Skip to content

Commit 27942bc

Browse files
authored
Merge pull request rails#50347 from iamradioactive/fix_derived_foreign_key
Fix derived foreign key to return correctly when association id is part of query constraints
2 parents 94faed4 + c82bfcd commit 27942bc

File tree

2 files changed

+10
-0
lines changed

2 files changed

+10
-0
lines changed

activerecord/lib/active_record/reflection.rb

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -797,6 +797,8 @@ def derive_fk_query_constraints(foreign_key)
797797
MSG
798798
end
799799

800+
return foreign_key if primary_query_constraints.include?(foreign_key)
801+
800802
first_key, last_key = primary_query_constraints
801803

802804
if first_key == owner_pk

activerecord/test/cases/reflection_test.rb

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -620,6 +620,14 @@ def test_association_primary_key_uses_explicit_primary_key_option_as_first_prior
620620
assert_equal "id", actual
621621
end
622622

623+
def test_belongs_to_reflection_with_query_constraints_infers_correct_foreign_key
624+
blog_foreign_key = Sharded::Comment.reflect_on_association(:blog).foreign_key
625+
blog_post_foreign_key = Sharded::Comment.reflect_on_association(:blog_post).foreign_key
626+
627+
assert_equal "blog_id", blog_foreign_key
628+
assert_equal ["blog_id", "blog_post_id"], blog_post_foreign_key
629+
end
630+
623631
private
624632
def assert_reflection(klass, association, options)
625633
assert reflection = klass.reflect_on_association(association)

0 commit comments

Comments
 (0)