mirror of https://github.com/rails/rails
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:
commit
0a6532db99
|
@ -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
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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
|
||||
|
|
Loading…
Reference in New Issue