Merge pull request #50321 from fatkodima/fix-polymorphic-belongs_to-with-query_constraints

Fix polymorphic `belongs_to` to correctly use parent's `query_constraints`
This commit is contained in:
Eileen M. Uchitelle 2023-12-11 10:12:44 -05:00 committed by GitHub
commit 0a6532db99
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 12 additions and 1 deletions

View File

@ -870,7 +870,7 @@ module ActiveRecord
def association_primary_key(klass = nil)
if primary_key = options[:primary_key]
@association_primary_key ||= -primary_key.to_s
elsif !polymorphic? && ((klass || self.klass).has_query_constraints? || options[:query_constraints])
elsif (klass || self.klass).has_query_constraints? || options[:query_constraints]
(klass || self.klass).composite_query_constraints_list
elsif (klass || self.klass).composite_primary_key?
# If klass has composite primary key of shape [:<tenant_key>, :id], infer primary_key as :id

View File

@ -284,6 +284,14 @@ class AssociationsTest < ActiveRecord::TestCase
assert_equal(blog_post, comment.blog_post_by_id)
end
def test_polymorphic_belongs_to_uses_parent_query_constraints
parent_post = sharded_blog_posts(:great_post_blog_one)
child_post = Sharded::BlogPost.create!(title: "Child post", blog_id: parent_post.blog_id, parent: parent_post)
child_post.reload # reload to forget the parent association
assert_equal parent_post, child_post.parent
end
def test_preloads_model_with_query_constraints_by_explicitly_configured_fk_and_pk
comment = sharded_comments(:great_comment_blog_post_one)
comments = Sharded::Comment.where(id: comment.id).preload(:blog_post_by_id).to_a

View File

@ -5,9 +5,11 @@ module Sharded
self.table_name = :sharded_blog_posts
query_constraints :blog_id, :id
belongs_to :parent, class_name: name, polymorphic: true
belongs_to :blog
has_many :comments
has_many :delete_comments, class_name: "Sharded::Comment", dependent: :delete_all
has_many :children, class_name: name, as: :parent
has_many :blog_post_tags
has_many :tags, through: :blog_post_tags

View File

@ -313,6 +313,7 @@ ActiveRecord::Schema.define do
create_table :sharded_blog_posts, force: true do |t|
t.string :title
t.references :parent, polymorphic: true
t.integer :blog_id
t.integer :revision
end