aboutsummaryrefslogblamecommitdiffstats
path: root/activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb
blob: 55d789c66abada392ed2e1a96f5b0444d03ee992 (plain) (tree)
1
2
3
4
5
6
7
8
9
10
11

                             

                     
                                                        
                                                                         




                                             
             
 

                                
                                                                                      

           
                                     
                                        

           
                                          
                                                         

           
                                           
                                                                                
           

                       

                                                                                
           


       
# frozen_string_literal: true

module ActiveRecord
  module Associations
    # = Active Record Belongs To Polymorphic Association
    class BelongsToPolymorphicAssociation < BelongsToAssociation #:nodoc:
      def klass
        type = owner[reflection.foreign_type]
        type.presence && type.constantize
      end

      private

        def replace_keys(record)
          super
          owner[reflection.foreign_type] = record ? record.class.base_class.name : nil
        end

        def different_target?(record)
          super || record.class != klass
        end

        def inverse_reflection_for(record)
          reflection.polymorphic_inverse_of(record.class)
        end

        def raise_on_type_mismatch!(record)
          # A polymorphic association cannot have a type mismatch, by definition
        end

        def stale_state
          foreign_key = super
          foreign_key && [foreign_key.to_s, owner[reflection.foreign_type].to_s]
        end
    end
  end
end