Class: Mongoid::Associations::HasManyAssociation

Inherits:
Array
  • Object
show all
Defined in:
lib/mongoid/associations/has_many_association.rb

Overview

:nodoc:

Instance Method Summary collapse

Methods included from Extensions::Array::Conversions

#mongoidize

Constructor Details

#initialize(association_name, document) ⇒ HasManyAssociation

Creates the new association by finding the attributes in the parent document with its name, and instantiating a new document for each one found. These will then be put in an internal array.

This then delegated all methods to the array class since this is essentially a proxy to an array itself.



12
13
14
15
16
17
18
19
20
21
# File 'lib/mongoid/associations/has_many_association.rb', line 12

def initialize(association_name, document)
  @klass = association_name.to_s.classify.constantize
  attributes = document.attributes[association_name]
  @documents = attributes ? attributes.collect do |attribute|
    child = @klass.new(attribute)
    child.parent = document
    child
  end : []
  super(@documents)
end

Instance Method Details

#build(attributes) ⇒ Object

Builds a new Document and adds it to the association collection. The document created will be of the same class as the others in the association, and the attributes will be passed into the constructor.

Returns the newly created object.



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

def build(attributes)
  object = @klass.new(attributes)
  push(object)
  object
end

#find(param) ⇒ Object

Finds a document in this association. If :all is passed, returns all the documents If an id is passed, will return the document for that id.



37
38
39
40
# File 'lib/mongoid/associations/has_many_association.rb', line 37

def find(param)
  return @documents if param == :all
  return detect { |document| document.id == param }
end