Class: MongoModel::Associations::HasManyByForeignKey::Association

Inherits:
Base::Association
  • Object
show all
Defined in:
lib/mongomodel/concerns/associations/has_many_by_foreign_key.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

#assign(doc) ⇒ Object


75
76
77
78
# File 'lib/mongomodel/concerns/associations/has_many_by_foreign_key.rb', line 75

def assign(doc)
  set_inverse_association(doc)
  doc.save(false) unless doc.new_record?
end

#build(*args, &block) ⇒ Object


49
50
51
52
53
# File 'lib/mongomodel/concerns/associations/has_many_by_foreign_key.rb', line 49

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

#create(*args) ⇒ Object


55
56
57
58
59
60
# File 'lib/mongomodel/concerns/associations/has_many_by_foreign_key.rb', line 55

def create(*args)
  scoped.create(*args) do |doc|
    set_inverse_association(doc)
    yield doc if block_given?
  end
end

#create!(*args) ⇒ Object


62
63
64
65
66
67
# File 'lib/mongomodel/concerns/associations/has_many_by_foreign_key.rb', line 62

def create!(*args)
  scoped.create!(*args) do |doc|
    set_inverse_association(doc)
    yield doc if block_given?
  end
end

#ensure_class(array) ⇒ Object


94
95
96
# File 'lib/mongomodel/concerns/associations/has_many_by_foreign_key.rb', line 94

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

#find_targetObject


43
44
45
46
47
# File 'lib/mongomodel/concerns/associations/has_many_by_foreign_key.rb', line 43

def find_target
  scoped.each { |doc|
    doc.send("#{inverse_of}=", instance) if doc.respond_to?("#{inverse_of}=")
  } + new_documents
end

#replace(array) ⇒ Object


69
70
71
72
73
# File 'lib/mongomodel/concerns/associations/has_many_by_foreign_key.rb', line 69

def replace(array)
  ensure_class(array)
  array.each { |doc| assign(doc) }
  super
end

#scopedObject


90
91
92
# File 'lib/mongomodel/concerns/associations/has_many_by_foreign_key.rb', line 90

def scoped
  definition.scope.where(foreign_key => instance.id).on_load { |doc| set_inverse_association(doc) }
end

#unset(doc) ⇒ Object


80
81
82
83
84
85
86
87
88
# File 'lib/mongomodel/concerns/associations/has_many_by_foreign_key.rb', line 80

def unset(doc)
  if doc.respond_to?("#{inverse_of}=")
    doc.send("#{inverse_of}=", nil) if doc.send(inverse_of) == instance
  else
    doc[foreign_key] = nil if doc[foreign_key] == instance.id
  end

  doc.save(false) unless doc.new_record?
end