Skip to content

Commit c82bfcd

Browse files
Fix derived foreign key to return correctly when association id is part of query constraints
1 parent 8278626 commit c82bfcd

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
@@ -804,6 +804,8 @@ def derive_fk_query_constraints(foreign_key)
804804
MSG
805805
end
806806

807+
return foreign_key if primary_query_constraints.include?(foreign_key)
808+
807809
first_key, last_key = primary_query_constraints
808810

809811
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
@@ -653,6 +653,14 @@ def test_association_primary_key_uses_explicit_primary_key_option_as_first_prior
653653
assert_equal "id", actual
654654
end
655655

656+
def test_belongs_to_reflection_with_query_constraints_infers_correct_foreign_key
657+
blog_foreign_key = Sharded::Comment.reflect_on_association(:blog).foreign_key
658+
blog_post_foreign_key = Sharded::Comment.reflect_on_association(:blog_post).foreign_key
659+
660+
assert_equal "blog_id", blog_foreign_key
661+
assert_equal ["blog_id", "blog_post_id"], blog_post_foreign_key
662+
end
663+
656664
private
657665
def assert_reflection(klass, association, options)
658666
assert reflection = klass.reflect_on_association(association)

0 commit comments

Comments
 (0)