Module: MongoDoc::ReferencesMany

Defined in:
lib/mongo_doc/references_many.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.ids_from_objects(objects) ⇒ Object



4
5
6
7
8
9
10
# File 'lib/mongo_doc/references_many.rb', line 4

def self.ids_from_objects(objects)
  if objects.blank?
    []
  else
    objects.map {|obj| obj._id }
  end
end

.ids_from_strings_or_ids(ids_or_strings) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/mongo_doc/references_many.rb', line 12

def self.ids_from_strings_or_ids(ids_or_strings)
  if ids_or_strings.blank?
    []
  else
    ids_or_strings.map do |item|
      if String === item
        ::BSON::ObjectId.cast_from_string(item)
      else
        item
      end
    end
  end
end

.objects_from_ids(klass, ids) ⇒ Object



26
27
28
29
30
31
32
# File 'lib/mongo_doc/references_many.rb', line 26

def self.objects_from_ids(klass, ids)
  if ids.blank?
    []
  else
    klass.find(*ids).entries
  end
end

.objects_from_refs(refs) ⇒ Object



34
35
36
37
38
39
40
# File 'lib/mongo_doc/references_many.rb', line 34

def self.objects_from_refs(refs)
  if refs.blank?
    []
  else
    refs.map {|ref| References.dereference(ref) }
  end
end

.refs_from_objects(objects) ⇒ Object



42
43
44
45
46
47
48
# File 'lib/mongo_doc/references_many.rb', line 42

def self.refs_from_objects(objects)
  if objects.blank?
    []
  else
    objects.map {|obj| ::BSON::DBRef.new(obj.class.collection_name, obj._id) }
  end
end

Instance Method Details

#references_many(*args) ⇒ Object

Declare reference to an array of Documents. The references can be ObjectId references or a BSON::DBRef, but cannot be both.

Use an ObjectId reference when you have a simple reference or will be referencing a single polymorphic collection. Example:

references_many :addresses references_many :addresses, :as => :work_address+

  • classname

    name of Document type as an underscore symbol or string

  • options

    :as specifies the name of the attribute, defaults to

classname

Use a BSON::DBRef when you need a reference to multiple collections. Example:

references_many :as_ref => :work_address

  • required

    :as_ref name of the attribute



69
70
71
72
73
74
75
76
77
78
# File 'lib/mongo_doc/references_many.rb', line 69

def references_many(*args)
  options = args.extract_options!

  if options.has_key?(:as_ref)
    references_many_by_dbref(options[:as_ref].to_s)
  else
    klass = args[0].to_s.singularize.camelize
    references_many_by_id(klass, options[:as].try(:to_s) || klass.demodulize.underscore.pluralize)
  end
end