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

Inherits:
Base
  • Object
show all
Defined in:
lib/mongo_mapper/plugins/associations/belongs_to_association.rb

Direct Known Subclasses

OneAssociation

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, #foreign_key, #in_array?, #initialize, #ivar, #klass, #polymorphic?, #type_key_name

Constructor Details

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

Instance Method Details

#autosave?Boolean

Returns:



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

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

#embeddable?Boolean

Returns:



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

def embeddable?
  false
end

#proxy_classObject



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

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

#setup(model) ⇒ Object



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
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/mongo_mapper/plugins/associations/belongs_to_association.rb', line 15

def setup(model)
  model.associations_module.module_eval <<-end_eval
    def #{name}
      proxy = get_proxy(associations[#{name.inspect}])
      proxy.nil? ? nil : proxy
    end

    def #{name}=(value)
      association = associations[#{name.inspect}]
      proxy = get_proxy(association)

      if proxy.nil? || proxy.target != value
        proxy = build_proxy(association)
      end

      proxy.replace(value)
      value
    end

    def #{name}?
      get_proxy(associations[#{name.inspect}]).present?
    end

    def build_#{name}(attrs={})
      get_proxy(associations[#{name.inspect}]).build(attrs)
    end

    def create_#{name}(attrs={})
      get_proxy(associations[#{name.inspect}]).create(attrs)
    end

    def create_#{name}!(attrs={})
      get_proxy(associations[#{name.inspect}]).create!(attrs)
    end
  end_eval
end