Method: Apidae::Selection.add_or_update

Defined in:
app/models/apidae/selection.rb

.add_or_update(selection_data, apidae_proj_id) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'app/models/apidae/selection.rb', line 19

def self.add_or_update(selection_data, apidae_proj_id)
  apidae_sel = Selection.where(apidae_id: selection_data[:id]).first_or_initialize
  apidae_sel.label = selection_data[:nom]
  apidae_sel.apidae_project_id = apidae_proj_id
  apidae_sel.save!

  # Note : should be done with basic collection assignment, but can't make it work...
  current_objs = apidae_sel.objects.collect {|obj| obj.apidae_id}
  imported_objs = selection_data[:objetsTouristiques].blank? ? [] : selection_data[:objetsTouristiques].collect {|obj| obj[:id]}

  added = imported_objs - current_objs
  removed = current_objs - imported_objs

  added.each do |o|
    obj = Obj.find_by_apidae_id(o)
    if obj
      SelectionObject.create(apidae_selection_id: apidae_sel.id, apidae_object_id: obj.id)
    else
      logger.error "Object #{o} referenced in selection #{apidae_sel.apidae_id} and project #{apidae_sel.apidae_project.apidae_id} is unknown"
    end
  end

  removed_ids = Obj.where(apidae_id: removed).map {|o| o.id}
  SelectionObject.where(apidae_selection_id: apidae_sel.id, apidae_object_id: removed_ids).delete_all
end