Class: ActiveRecord::Associations::CollectionAssociation

Inherits:
Object
  • Object
show all
Defined in:
lib/activehistory/adapters/active_record.rb

Instance Method Summary collapse

Instance Method Details

#delete_all(dependent = nil) ⇒ Object



329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
# File 'lib/activehistory/adapters/active_record.rb', line 329

def delete_all(dependent = nil)
  activehistory_encapsulate do
    if dependent && ![:nullify, :delete_all].include?(dependent)
      raise ArgumentError, "Valid values are :nullify or :delete_all"
    end

    dependent = if dependent
                  dependent
                elsif options[:dependent] == :destroy
                  :delete_all
                else
                  options[:dependent]
                end

    if dependent == :delete_all

    elsif !owner.id.nil?
      removed_ids = self.scope.pluck(:id)
    
      action = owner.activehistory_event.action_for(self.reflection.active_record, owner.id, {
        type: :update,
        timestamp: owner.activehistory_timestamp
      })
      
      diff_key = "#{self.reflection.name.to_s.singularize}_ids"
      action.diff ||= {}
      action.diff[diff_key] ||= [[], []]
      action.diff[diff_key][0] |= removed_ids
    
      ainverse_of = self.klass.reflect_on_association(self.options[:inverse_of])
      if ainverse_of
        removed_ids.each do |removed_id|
          action = owner.activehistory_event.action_for(ainverse_of.active_record, removed_id, {
            type: :update,
            timestamp: owner.activehistory_timestamp
          })
          action.diff ||= {}
          if ainverse_of.collection?
            diff_key = "#{ainverse_of.name.to_s.singularize}_ids"
            action.diff[diff_key] ||= [[], []]
            action.diff[diff_key][0] |= [owner.id]
          else
            diff_key = "#{ainverse_of.name}_id"
            action.diff[diff_key] ||= [owner.id, nil]
          end
        end
      end
    end

    delete_or_nullify_all_records(dependent).tap do
      reset
      loaded!
    end
  end
end