Class: ActiveRecord::Associations::BelongsToAssociation

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

Overview

Active Record Belongs To Association

Direct Known Subclasses

BelongsToPolymorphicAssociation

Instance Attribute Summary

Attributes inherited from Association

#owner, #reflection, #target

Instance Method Summary collapse

Methods inherited from SingularAssociation

#build, #force_reload_reader, #reader, #writer

Methods inherited from Association

#association_scope, #create, #create!, #extensions, #initialize, #initialize_attributes, #klass, #load_target, #loaded!, #loaded?, #marshal_dump, #marshal_load, #reload, #remove_inverse_instance, #reset_scope, #scope, #set_inverse_instance, #set_inverse_instance_from_queries, #stale_target?, #target_scope

Constructor Details

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

Instance Method Details

#decrement_countersObject

:nodoc:



52
53
54
# File 'lib/active_record/associations/belongs_to_association.rb', line 52

def decrement_counters # :nodoc:
  update_counters(-1)
end

#default(&block) ⇒ Object



39
40
41
# File 'lib/active_record/associations/belongs_to_association.rb', line 39

def default(&block)
  writer(owner.instance_exec(&block)) if reader.nil?
end

#handle_dependencyObject

:nodoc:



7
8
9
10
11
12
13
14
15
16
17
# File 'lib/active_record/associations/belongs_to_association.rb', line 7

def handle_dependency
  return unless load_target

  case options[:dependent]
  when :destroy
    target.destroy
    raise ActiveRecord::Rollback unless target.destroyed?
  else
    target.send(options[:dependent])
  end
end

#increment_countersObject

:nodoc:



56
57
58
# File 'lib/active_record/associations/belongs_to_association.rb', line 56

def increment_counters # :nodoc:
  update_counters(1)
end

#inversed_from(record) ⇒ Object



34
35
36
37
# File 'lib/active_record/associations/belongs_to_association.rb', line 34

def inversed_from(record)
  replace_keys(record)
  super
end

#replace(record) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/active_record/associations/belongs_to_association.rb', line 19

def replace(record)
  if record
    raise_on_type_mismatch!(record)
    update_counters_on_replace(record)
    set_inverse_instance(record)
    @updated = true
  else
    decrement_counters
  end

  replace_keys(record)

  self.target = record
end

#resetObject



43
44
45
46
# File 'lib/active_record/associations/belongs_to_association.rb', line 43

def reset
  super
  @updated = false
end

#target_changed?Boolean

Returns:

  • (Boolean)


60
61
62
# File 'lib/active_record/associations/belongs_to_association.rb', line 60

def target_changed?
  owner.saved_change_to_attribute?(reflection.foreign_key)
end

#updated?Boolean

Returns:

  • (Boolean)


48
49
50
# File 'lib/active_record/associations/belongs_to_association.rb', line 48

def updated?
  @updated
end