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



302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
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
# File 'lib/activehistory/adapters/active_record.rb', line 302

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

    else
      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