Class: ActiveRecord::Associations::HasOneAssociation

Inherits:
SingularAssociation show all
Defined in:
activerecord/lib/active_record/associations/has_one_association.rb

Overview

:nodoc:

Direct Known Subclasses

HasOneThroughAssociation

Instance Attribute Summary

Attributes inherited from Association

#owner, #reflection, #target

Instance Method Summary collapse

Methods inherited from SingularAssociation

#build, #create, #create!, #reader, #writer

Methods inherited from Association

#aliased_table_name, #association_scope, #initialize, #interpolate, #klass, #load_target, #loaded!, #loaded?, #reload, #reset, #reset_scope, #scoped, #set_inverse_instance, #stale_target?, #target_scope

Constructor Details

This class inherits a constructor from ActiveRecord::Associations::Association

Instance Method Details

#delete(method = options[:dependent]) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
# File 'activerecord/lib/active_record/associations/has_one_association.rb', line 31

def delete(method = options[:dependent])
  if load_target
    case method
      when :delete
        target.delete
      when :destroy
        target.destroy
      when :nullify
        target.update_attribute(reflection.foreign_key, nil)
    end
  end
end

#replace(record, save = true) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'activerecord/lib/active_record/associations/has_one_association.rb', line 7

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

  reflection.klass.transaction do
    if target && target != record
      remove_target!(options[:dependent]) unless target.destroyed?
    end

    if record
      set_owner_attributes(record)
      set_inverse_instance(record)

      if owner.persisted? && 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

  self.target = record
end