Class: CouchFoo::Associations::BelongsToAssociation

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

Overview

:nodoc:

Direct Known Subclasses

HasOneAssociation

Instance Method Summary collapse

Methods inherited from AssociationProxy

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

Constructor Details

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

Dynamic Method Handling

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

Instance Method Details

#build(attributes = {}) ⇒ Object



8
9
10
# File 'lib/couch_foo/associations/belongs_to_association.rb', line 8

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

#create(attributes = {}) ⇒ Object



4
5
6
# File 'lib/couch_foo/associations/belongs_to_association.rb', line 4

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

#replace(record) ⇒ Object



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

def replace(record)
  counter_cache_name = @reflection.counter_cache_property

  if record.nil?
    if counter_cache_name && !@owner.new_record?
      @reflection.klass.decrement_counter(counter_cache_name, @owner[@reflection.primary_key_name]) 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?
      @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 unless record.new_record?
    @updated = true
  end

  loaded
  record
end

#updated?Boolean

Returns:



38
39
40
# File 'lib/couch_foo/associations/belongs_to_association.rb', line 38

def updated?
  @updated
end