Class: Mongoid::Associations::BelongsToRelated
- 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
Class Method Summary collapse
-
.instantiate(document, options, target = nil) ⇒ Object
Instantiate a new
BelongsToRelated
or return nil if the foreign key is nil. -
.macro ⇒ Object
Returns the macro used to create the association.
-
.update(target, document, options) ⇒ Object
Perform an update of the relationship of the parent and child.
Instance Method Summary collapse
-
#initialize(document, foreign_key, options, target = nil) ⇒ BelongsToRelated
constructor
Initializing a related association only requires looking up the object by its id.
Methods inherited from Proxy
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, , target = nil) = @target = target || .klass.find(foreign_key) extends() 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, , target = nil) foreign_key = document.send(.foreign_key) foreign_key.blank? ? nil : new(document, foreign_key, , target) end |
.macro ⇒ Object
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, ) document.send("#{options.foreign_key}=", target ? target.id : nil) instantiate(document, , target) end |