Skip to content

Commit

Permalink
Merge pull request #50319 from fatkodima/fix-where-for-polymorphic-cpk
Browse files Browse the repository at this point in the history
Fix predicate builder for polymorphic models referencing models with composite primary keys
  • Loading branch information
eileencodes committed Dec 11, 2023
2 parents 0a6532d + 0663b44 commit 0745043
Show file tree
Hide file tree
Showing 6 changed files with 41 additions and 1 deletion.
Expand Up @@ -43,7 +43,12 @@ def klass(value)

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
Expand Down
Expand Up @@ -63,6 +63,12 @@ def test_where_on_polymorphic_association_with_empty_array
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!
Expand Down
2 changes: 2 additions & 0 deletions activerecord/test/models/cpk.rb
Expand Up @@ -8,3 +8,5 @@
require_relative "cpk/order_tag"
require_relative "cpk/tag"
require_relative "cpk/chapter"
require_relative "cpk/post"
require_relative "cpk/comment"
8 changes: 8 additions & 0 deletions activerecord/test/models/cpk/comment.rb
@@ -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
8 changes: 8 additions & 0 deletions activerecord/test/models/cpk/post.rb
@@ -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
11 changes: 11 additions & 0 deletions activerecord/test/schema/schema.rb
Expand Up @@ -261,6 +261,17 @@
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
Expand Down

0 comments on commit 0745043

Please sign in to comment.