Class: ActiveRecord::Associations::BelongsToAssociation

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

Overview

:nodoc:

Instance Method Summary collapse

Methods inherited from AssociationProxy

#===, #aliased_table_name, #conditions, #initialize, #inspect, #loaded, #loaded?, #proxy_owner, #proxy_reflection, #proxy_respond_to?, #proxy_target, #reload, #reset, #respond_to?, #send, #target, #target=

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



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

def build(attributes = {})
  replace(@reflection.build_association(attributes))
end

#create(attributes = {}) ⇒ Object



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

def create(attributes = {})
  replace(@reflection.create_association(attributes))
end

#replace(record) ⇒ Object



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
# File 'lib/active_record/associations/belongs_to_association.rb', line 13

def replace(record)
  counter_cache_name = @reflection.counter_cache_column

  if record.nil?
    if counter_cache_name && !@owner.new_record?
      @reflection.klass.decrement_counter(counter_cache_name, previous_record_id) if @owner[@reflection.primary_key_name]
    end

    @target = @owner[@reflection.primary_key_name] = nil
  else
    raise_on_type_mismatch(record)

    if counter_cache_name && !@owner.new_record? && record.id != @owner[@reflection.primary_key_name]
      @reflection.klass.increment_counter(counter_cache_name, record.id)
      @reflection.klass.decrement_counter(counter_cache_name, @owner[@reflection.primary_key_name]) if @owner[@reflection.primary_key_name]
    end

    @target = (AssociationProxy === record ? record.target : record)
    @owner[@reflection.primary_key_name] = record_id(record) unless record.new_record?
    @updated = true
  end

  set_inverse_instance(record, @owner)

  loaded
  record
end

#updated?Boolean

Returns:

  • (Boolean)


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

def updated?
  @updated
end