diff --git a/activerecord/lib/active_record/relation/predicate_builder.rb b/activerecord/lib/active_record/relation/predicate_builder.rb index 9a14c2a627..9049b09d9d 100644 --- a/activerecord/lib/active_record/relation/predicate_builder.rb +++ b/activerecord/lib/active_record/relation/predicate_builder.rb @@ -93,11 +93,8 @@ module ActiveRecord # PriceEstimate.where(estimate_of: treasure) associated_table = table.associated_table(key) if associated_table.polymorphic_association? - case value.is_a?(Array) ? value.first : value - when Base, Relation - value = [value] unless value.is_a?(Array) - klass = PolymorphicArrayValue - end + value = [value] unless value.is_a?(Array) + klass = PolymorphicArrayValue elsif associated_table.through_association? next associated_table.predicate_builder.expand_from_hash( associated_table.primary_key => value diff --git a/activerecord/lib/active_record/relation/predicate_builder/polymorphic_array_value.rb b/activerecord/lib/active_record/relation/predicate_builder/polymorphic_array_value.rb index 296a0c6c1c..808fff9561 100644 --- a/activerecord/lib/active_record/relation/predicate_builder/polymorphic_array_value.rb +++ b/activerecord/lib/active_record/relation/predicate_builder/polymorphic_array_value.rb @@ -10,10 +10,10 @@ module ActiveRecord def queries type_to_ids_mapping.map do |type, ids| - { - associated_table.join_foreign_type => type, - associated_table.join_foreign_key => ids - } + query = {} + query[associated_table.join_foreign_type] = type if type + query[associated_table.join_foreign_key] = ids + query end end @@ -23,7 +23,7 @@ module ActiveRecord def type_to_ids_mapping default_hash = Hash.new { |hsh, key| hsh[key] = [] } values.each_with_object(default_hash) do |value, hash| - hash[klass(value).polymorphic_name] << convert_to_id(value) + hash[klass(value)&.polymorphic_name] << convert_to_id(value) end end @@ -46,6 +46,8 @@ module ActiveRecord value._read_attribute(primary_key(value)) when Relation value.select(primary_key(value)) + else + value end end end diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb index db5063c197..62f32e61be 100644 --- a/activerecord/test/cases/associations/belongs_to_associations_test.rb +++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb @@ -44,6 +44,11 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase assert_equal [authors(:david)], Author.where(owned_essay: essays(:david_modest_proposal)) end + def test_where_on_polymorphic_association_with_nil + assert_equal comments(:greetings), Comment.where(author: nil).first + assert_equal comments(:greetings), Comment.where(author: [nil]).first + end + def test_assigning_belongs_to_on_destroyed_object client = Client.create!(name: "Client") client.destroy!