aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/associations/has_one_association.rb
blob: a4332a05112eb1bfbc7b63074a0c1c6c42b55f2a (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
module ActiveRecord
  # = Active Record Belongs To Has One Association
  module Associations
    class HasOneAssociation < AssociationProxy #:nodoc:
      def create(attributes = {})
        new_record(:create_association, attributes)
      end

      def create!(attributes = {})
        new_record(:create_association!, attributes)
      end

      def build(attributes = {})
        new_record(:build_association, attributes)
      end

      def replace(record, save = true)
        record = record.target if AssociationProxy === record
        raise_on_type_mismatch(record) unless record.nil?
        load_target

        if @target && @target != record
          remove_target!(@reflection.options[:dependent])
        end

        if record
          set_owner_attributes(record)
          set_inverse_instance(record)
        end

        @target = record
        loaded

        if @owner.persisted? && record && save
          record.save && self
        else
          record && self
        end
      end

      private
        def find_target
          scoped.first.tap { |record| set_inverse_instance(record) }
        end

        def association_scope
          super.order(@reflection.options[:order])
        end

        alias creation_attributes construct_owner_attributes

        def new_record(method, attributes)
          record = scoped.scoping { @reflection.send(method, attributes) }
          replace(record, false)
          record
        end

        def remove_target!(method)
          if [:delete, :destroy].include?(method)
            @target.send(method)
          else
            @target[@reflection.foreign_key] = nil

            if @target.persisted? && @owner.persisted?
              unless @target.save
                @target[@reflection.foreign_key] = @target.send("#{@reflection.foreign_key}_was")
                raise RecordNotSaved, "Failed to remove the existing associated #{@reflection.name}. " +
                                      "The record failed to save when after its foreign key was set to nil."
              end
            end
          end
        end
    end
  end
end