aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/associations/has_one_association.rb
blob: 5ea9577301f0f213113aef763a2803b106deb8a9 (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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
module ActiveRecord
  # = Active Record Has One Association
  module Associations
    class HasOneAssociation < SingularAssociation #:nodoc:
      include ForeignAssociation

      def handle_dependency
        case options[:dependent]
        when :restrict_with_exception
          raise ActiveRecord::DeleteRestrictionError.new(reflection.name) if load_target

        when :restrict_with_error
          if load_target
            record = owner.class.human_attribute_name(reflection.name).downcase
            message = owner.errors.generate_message(:base, :'restrict_dependent_destroy.one', record: record, raise: true) rescue nil
            if message
              ActiveSupport::Deprecation.warn(<<-MESSAGE.squish)
                The error key `:'restrict_dependent_destroy.one'` has been deprecated and will be removed in Rails 5.1.
                Please use `:'restrict_dependent_destroy.has_one'` instead.
              MESSAGE
            end
            owner.errors.add(:base, message || :'restrict_dependent_destroy.has_one', record: record)
            throw(:abort)
          end

        else
          delete
        end
      end

      def replace(record, save = true)
        raise_on_type_mismatch!(record) if record
        load_target

        return target unless target || record

        assigning_another_record = target != record
        if assigning_another_record || record.changed?
          save &&= owner.persisted?

          transaction_if(save) do
            remove_target!(options[:dependent]) if target && !target.destroyed? && assigning_another_record

            if record
              set_owner_attributes(record)
              set_inverse_instance(record)

              if save && !record.save
                nullify_owner_attributes(record)
                set_owner_attributes(target) if target
                raise RecordNotSaved, "Failed to save the new associated #{reflection.name}."
              end
            end
          end
        end

        self.target = record
      end

      def delete(method = options[:dependent])
        if load_target
          case method
          when :delete
            target.delete
          when :destroy
            target.destroy
          when :nullify
            target.update_columns(reflection.foreign_key => nil) if target.persisted?
          end
        end
      end

      private

        # The reason that the save param for replace is false, if for create (not just build),
        # is because the setting of the foreign keys is actually handled by the scoping when
        # the record is instantiated, and so they are set straight away and do not need to be
        # updated within replace.
        def set_new_record(record)
          replace(record, false)
        end

        def remove_target!(method)
          case method
          when :delete
            target.delete
          when :destroy
            target.destroy
            else
            nullify_owner_attributes(target)

            if target.persisted? && owner.persisted? && !target.save
              set_owner_attributes(target)
              raise RecordNotSaved, "Failed to remove the existing associated #{reflection.name}. " +
                                    "The record failed to save after its foreign key was set to nil."
            end
          end
        end

        def nullify_owner_attributes(record)
          record[reflection.foreign_key] = nil
        end

        def transaction_if(value)
          if value
            reflection.klass.transaction { yield }
          else
            yield
          end
        end
    end
  end
end