Merge pull request #50347 from iamradioactive/fix_derived_foreign_key

Fix derived foreign key to return correctly when association id is part of query constraints
This commit is contained in:
Eileen M. Uchitelle 2024-03-19 09:14:19 -04:00 committed by GitHub
commit 27942bc382
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 10 additions and 0 deletions

View File

@ -797,6 +797,8 @@ module ActiveRecord
MSG
end
return foreign_key if primary_query_constraints.include?(foreign_key)
first_key, last_key = primary_query_constraints
if first_key == owner_pk

View File

@ -620,6 +620,14 @@ class ReflectionTest < ActiveRecord::TestCase
assert_equal "id", actual
end
def test_belongs_to_reflection_with_query_constraints_infers_correct_foreign_key
blog_foreign_key = Sharded::Comment.reflect_on_association(:blog).foreign_key
blog_post_foreign_key = Sharded::Comment.reflect_on_association(:blog_post).foreign_key
assert_equal "blog_id", blog_foreign_key
assert_equal ["blog_id", "blog_post_id"], blog_post_foreign_key
end
private
def assert_reflection(klass, association, options)
assert reflection = klass.reflect_on_association(association)