aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb
blob: 90eff7399c2fc6c3d966f49fa0e791a78cb68b34 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
module ActiveRecord
  # = Active Record Belongs To Polymorphic Association
  module Associations
    class BelongsToPolymorphicAssociation < AssociationProxy #:nodoc:
      def replace(record)
        if record.nil?
          @target = @owner[@reflection.primary_key_name] = @owner[@reflection.options[:foreign_type]] = nil
        else
          @target = (AssociationProxy === record ? record.target : record)

          @owner[@reflection.primary_key_name] = record_id(record)
          @owner[@reflection.options[:foreign_type]] = record.class.base_class.name.to_s

          @updated = true
        end

        set_inverse_instance(record)
        loaded
        record
      end

      def updated?
        @updated
      end

      def stale_target?
        if @target && @target.persisted?
          target_id    = @target.send(@reflection.association_primary_key).to_s
          foreign_key  = @owner.send(@reflection.primary_key_name).to_s
          target_type  = @target.class.base_class.name
          foreign_type = @owner.send(@reflection.options[:foreign_type]).to_s

          target_id != foreign_key || target_type != foreign_type
        else
          false
        end
      end

      private

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

        def invertible_for?(record)
          inverse = inverse_reflection_for(record)
          inverse && inverse.macro == :has_one
        end

        def construct_find_scope
          { :conditions => conditions }
        end

        def find_target
          return nil if association_class.nil?

          target = association_class.send(:with_scope, :find => @scope[:find]) do
            association_class.find(
              @owner[@reflection.primary_key_name],
              :select  => @reflection.options[:select],
              :include => @reflection.options[:include]
            )
          end
          set_inverse_instance(target)
          target
        end

        def foreign_key_present
          !@owner[@reflection.primary_key_name].nil?
        end

        def record_id(record)
          record.send(@reflection.options[:primary_key] || :id)
        end

        def association_class
          @owner[@reflection.options[:foreign_type]] ? @owner[@reflection.options[:foreign_type]].constantize : nil
        end
    end
  end
end