Class: Mongoid::Associations::BelongsToRelated

Inherits:
Proxy show all
Defined in:
lib/mongoid/associations/belongs_to_related.rb

Overview

Represents a relational association to a “parent” object.

Instance Attribute Summary

Attributes inherited from Proxy

#options, #target

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Proxy

#extends, #method_missing

Constructor Details

#initialize(document, foreign_key, options, target = nil) ⇒ BelongsToRelated

Initializing a related association only requires looking up the object by its id.

Options:

document: The Document that contains the relationship. options: The association Options.



14
15
16
17
18
# File 'lib/mongoid/associations/belongs_to_related.rb', line 14

def initialize(document, foreign_key, options, target = nil)
  @options = options
  @target = target || options.klass.find(foreign_key)
  extends(options)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class Mongoid::Associations::Proxy

Class Method Details

.instantiate(document, options, target = nil) ⇒ Object

Instantiate a new BelongsToRelated or return nil if the foreign key is nil. It is preferrable to use this method over the traditional call to new.

Options:

document: The Document that contains the relationship. options: The association Options.



29
30
31
32
# File 'lib/mongoid/associations/belongs_to_related.rb', line 29

def instantiate(document, options, target = nil)
  foreign_key = document.send(options.foreign_key)
  foreign_key.blank? ? nil : new(document, foreign_key, options, target)
end

.macroObject

Returns the macro used to create the association.



35
36
37
# File 'lib/mongoid/associations/belongs_to_related.rb', line 35

def macro
  :belongs_to_related
end

.update(target, document, options) ⇒ Object

Perform an update of the relationship of the parent and child. This will assimilate the child Document into the parent’s object graph.

Options:

target: The target(parent) object document: The Document to update. options: The association Options

Example:

BelongsToRelated.update(person, game, options)



51
52
53
54
# File 'lib/mongoid/associations/belongs_to_related.rb', line 51

def update(target, document, options)
  document.send("#{options.foreign_key}=", target ? target.id : nil)
  instantiate(document, options, target)
end