Class: MongoModel::Associations::HasManyByIds::Association

Inherits:
Base::Association show all
Defined in:
lib/mongomodel/concerns/associations/has_many_by_ids.rb

Instance Attribute Summary

Attributes inherited from Base::Association

#definition, #instance

Instance Method Summary collapse

Methods inherited from Base::Association

#initialize, #proxy

Constructor Details

This class inherits a constructor from MongoModel::Associations::Base::Association

Instance Method Details

#build(*args, &block) ⇒ Object



60
61
62
63
64
# File 'lib/mongomodel/concerns/associations/has_many_by_ids.rb', line 60

def build(*args, &block)
  doc = scoped.new(*args, &block)
  new_documents << doc
  doc
end

#create(*args, &block) ⇒ Object



66
67
68
# File 'lib/mongomodel/concerns/associations/has_many_by_ids.rb', line 66

def create(*args, &block)
  scoped.create(*args, &block)
end

#ensure_class(array) ⇒ Object



74
75
76
# File 'lib/mongomodel/concerns/associations/has_many_by_ids.rb', line 74

def ensure_class(array)
  array.is_a?(Array) ? array.each { |i| super(i) } : super
end

#find_targetObject



51
52
53
54
55
56
57
58
# File 'lib/mongomodel/concerns/associations/has_many_by_ids.rb', line 51

def find_target
  if ids.any?
    docs = Array.wrap(definition.scope.where(:id.in => (ids - new_document_ids))) + new_documents
    docs.sort_by { |doc| ids.index(doc.id) }
  else
    []
  end
end

#idsObject



40
41
42
# File 'lib/mongomodel/concerns/associations/has_many_by_ids.rb', line 40

def ids
  instance[property_name]
end

#replace(array) ⇒ Object



44
45
46
47
48
49
# File 'lib/mongomodel/concerns/associations/has_many_by_ids.rb', line 44

def replace(array)
  ensure_class(array)

  instance[property_name] = array.map { |i| i.id }
  super
end

#scopedObject



70
71
72
# File 'lib/mongomodel/concerns/associations/has_many_by_ids.rb', line 70

def scoped
  definition.scope.where(:id.in => ids)
end