Method: ActiveNode::Associations::Association#save

Defined in:
lib/active_node/associations/association.rb

#save(fresh = false) ⇒ Object



102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/active_node/associations/association.rb', line 102

def save(fresh=false)
  #return unless @dirty
  #delete all relations missing in new target
  original_rels = fresh ? [] : owner.class.includes(reflection.name).build(owner.id).first.association(reflection.name).rels_reader
  original_rels.each do |r|
    unless ids_reader.include? r.other.id
      Neo.db.delete_relationship(r.id)
      original_rels.delete(r)
    end
  end

  #add relations missing in old target
  #if no rel_target proceed as before + set rel_target from db
  #if rel_target exists update persisted records and insert new records
  if @rel_target
    @rel_target.each { |r| r.save(self) }
  else
    @target.map do |n|
      original_rels.detect { |r| r.other.id == n.id }.tap { |o_r| o_r.try :other=, n } ||
          ActiveNode::Relationship.create!(n, self)
    end
  end
end