Class: ActiveRecord::Associations::BelongsToAssociation

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

Overview

:nodoc:

Direct Known Subclasses

HasOneAssociation

Instance Method Summary collapse

Methods inherited from AssociationProxy

#initialize, #loaded?, #method_missing, #proxy_respond_to?, #respond_to?

Constructor Details

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

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class ActiveRecord::Associations::AssociationProxy

Instance Method Details

#build(attributes = {}) ⇒ Object



21
22
23
24
25
# File 'lib/active_record/associations/belongs_to_association.rb', line 21

def build(attributes = {})
  record = @association_class.new(attributes)
  replace(record, true)
  record
end

#create(attributes = {}) ⇒ Object



15
16
17
18
19
# File 'lib/active_record/associations/belongs_to_association.rb', line 15

def create(attributes = {})
  record = build(attributes)
  record.save
  record
end

#nil?Boolean

Ugly workaround - .nil? is done in C and the method_missing trick doesn’t work when we pretend to be nil

Returns:

  • (Boolean)


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

def nil?
  load_target
  @target.nil?
end

#reloadObject



10
11
12
13
# File 'lib/active_record/associations/belongs_to_association.rb', line 10

def reload
  reset
  load_target
end

#replace(obj, dont_save = false) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
# File 'lib/active_record/associations/belongs_to_association.rb', line 27

def replace(obj, dont_save = false)
  if obj.nil?
    @target = @owner[@association_class_primary_key_name] = nil
  else
    raise_on_type_mismatch(obj) unless obj.nil?

    @target = obj
    @owner[@association_class_primary_key_name] = obj.id unless obj.new_record?
  end
  @loaded = true
end

#resetObject



5
6
7
8
# File 'lib/active_record/associations/belongs_to_association.rb', line 5

def reset
  @target = nil
  @loaded = false
end