Class: ForestLiana::HasManyDissociator

Inherits:
ApplicationController show all
Defined in:
app/services/forest_liana/has_many_dissociator.rb

Instance Method Summary collapse

Methods inherited from ApplicationController

#authenticate_user_from_jwt, #forest_user, #internal_server_error, papertrail?, #serialize_model, #serialize_models

Methods inherited from BaseController

#route_not_found

Constructor Details

#initialize(resource, association, params) ⇒ HasManyDissociator

Returns a new instance of HasManyDissociator.



3
4
5
6
7
8
9
# File 'app/services/forest_liana/has_many_dissociator.rb', line 3

def initialize(resource, association, params)
  @resource = resource
  @association = association
  @params = params
  @with_deletion = @params[:delete].to_s == 'true'
  @data = params['data']
end

Instance Method Details

#performObject



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'app/services/forest_liana/has_many_dissociator.rb', line 11

def perform
  @record = @resource.find(@params[:id])
  associated_records = @resource.find(@params[:id]).send(@association.name)

  remove_association = !@with_deletion || @association.macro == :has_and_belongs_to_many

  if @data.is_a?(Array)
    record_ids = @data.map { |record| record[:id] }
  elsif @data.dig('attributes').present?
    record_ids = ForestLiana::ResourcesGetter.get_ids_from_request(@params, forest_user)
  else
    record_ids = Array.new
  end

  if !record_ids.nil? && record_ids.any?
    if remove_association
      record_ids.each do |id|
        associated_records.delete(@association.klass.find(id))
      end
    end

    if @with_deletion
      record_ids = record_ids.select { |record_id| @association.klass.exists?(record_id) }
      @association.klass.destroy(record_ids)
    end
  end
end