Class: MongoMapper::Plugins::Associations::BelongsToAssociation

Inherits:
SingleAssociation show all
Defined in:
lib/mongo_mapper/plugins/associations/belongs_to_association.rb

Constant Summary

Constants inherited from Base

MongoMapper::Plugins::Associations::Base::AssociationOptions

Instance Attribute Summary

Attributes inherited from Base

#name, #options, #query_options

Instance Method Summary collapse

Methods inherited from Base

#as, #as?, #class_name, #counter_cache?, #foreign_key, #in_array?, #in_foreign_array?, #initialize, #ivar, #klass, #ordered?, #polymorphic?, #touch?

Constructor Details

This class inherits a constructor from MongoMapper::Plugins::Associations::Base

Instance Method Details

#add_counter_cacheObject



52
53
54
55
56
57
58
59
# File 'lib/mongo_mapper/plugins/associations/belongs_to_association.rb', line 52

def add_counter_cache
  options = {}
  if @options[:counter_cache] && @options[:counter_cache] != true
    options[:field] = @options[:counter_cache]
  end

  @model.counter_cache name, options
end

#add_touch_callbacksObject



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/mongo_mapper/plugins/associations/belongs_to_association.rb', line 30

def add_touch_callbacks
  name        = self.name
  method_name = :"belongs_to_touch_after_save_or_destroy_for_#{name}"
  touch       = options.fetch(:touch)

  @model.send(:define_method, method_name) do
    record = send(name)

    unless record.nil?
      if touch == true
        record.touch
      else
        record.touch(touch)
      end
    end
  end

  @model.after_save(method_name)
  @model.after_touch(method_name)
  @model.after_destroy(method_name)
end

#autosave?Boolean

Returns:



26
27
28
# File 'lib/mongo_mapper/plugins/associations/belongs_to_association.rb', line 26

def autosave?
  options.fetch(:autosave, false)
end

#embeddable?Boolean

Returns:



10
11
12
# File 'lib/mongo_mapper/plugins/associations/belongs_to_association.rb', line 10

def embeddable?
  false
end

#proxy_classObject



14
15
16
# File 'lib/mongo_mapper/plugins/associations/belongs_to_association.rb', line 14

def proxy_class
  @proxy_class ||= polymorphic? ? BelongsToPolymorphicProxy : BelongsToProxy
end

#setup(model) ⇒ Object



18
19
20
21
22
23
24
# File 'lib/mongo_mapper/plugins/associations/belongs_to_association.rb', line 18

def setup(model)
  model.key foreign_key, ObjectId unless model.key?(foreign_key)
  model.key type_key_name, String unless model.key?(type_key_name) if polymorphic?
  super
  add_touch_callbacks if touch?
  add_counter_cache if counter_cache?
end

#type_key_nameObject



6
7
8
# File 'lib/mongo_mapper/plugins/associations/belongs_to_association.rb', line 6

def type_key_name
  "#{as}_type"
end