Merge pull request #50319 from fatkodima/fix-where-for-polymorphic-cpk

Fix predicate builder for polymorphic models referencing models with composite primary keys
This commit is contained in:
Eileen M. Uchitelle 2023-12-11 10:20:07 -05:00 committed by GitHub
commit 0745043c7a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 41 additions and 1 deletions

View File

@ -43,7 +43,12 @@ module ActiveRecord
def convert_to_id(value)
if value.is_a?(Base)
value._read_attribute(primary_key(value))
primary_key = primary_key(value)
if primary_key.is_a?(Array)
primary_key.map { |column| value._read_attribute(column) }
else
value._read_attribute(primary_key)
end
elsif value.is_a?(Relation)
value.select(primary_key(value))
else

View File

@ -63,6 +63,12 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
assert_empty Comment.where(author: [])
end
def test_where_on_polymorphic_association_with_cpk
post = Cpk::Post.create!(title: "Welcome", author: "Mary")
post.comments << Cpk::Comment.create!
assert_equal 1, Cpk::Comment.where(commentable: post).count
end
def test_assigning_belongs_to_on_destroyed_object
client = Client.create!(name: "Client")
client.destroy!

View File

@ -8,3 +8,5 @@ require_relative "cpk/order_agreement"
require_relative "cpk/order_tag"
require_relative "cpk/tag"
require_relative "cpk/chapter"
require_relative "cpk/post"
require_relative "cpk/comment"

View File

@ -0,0 +1,8 @@
# frozen_string_literal: true
module Cpk
class Comment < ActiveRecord::Base
self.table_name = :cpk_comments
belongs_to :commentable, class_name: "Cpk::Post", query_constraints: %i[commentable_title commentable_author], polymorphic: true
end
end

View File

@ -0,0 +1,8 @@
# frozen_string_literal: true
module Cpk
class Post < ActiveRecord::Base
self.table_name = :cpk_posts
has_many :comments, class_name: "Cpk::Comment", query_constraints: %i[commentable_title commentable_author], as: :commentable
end
end

View File

@ -261,6 +261,17 @@ ActiveRecord::Schema.define do
t.string :name
end
create_table :cpk_posts, primary_key: [:title, :author], force: true do |t|
t.string :title
t.string :author
end
create_table :cpk_comments, force: true do |t|
t.string :commentable_title
t.string :commentable_author
t.string :commentable_type
end
create_table :cpk_reviews, force: true do |t|
t.integer :author_id
t.integer :number