Module: Finalizers::Model::ClassMethods

Defined in:
app/models/finalizers/model.rb

Instance Method Summary collapse

Instance Method Details

#erase_dependents(*assoc_list) ⇒ Object

if child models include Finalizers::Model, then use erase_dependents to perform a cascading erase. use this instead of has_many or has_one’s depdendent: :destroy (etc).



108
109
110
111
112
113
114
115
116
117
# File 'app/models/finalizers/model.rb', line 108

def erase_dependents(*assoc_list)
  wait_for_no_dependents(*assoc_list, erase_if_found: true)
  before_update do
    if state == 'deleted' && state_was != 'deleted'
      assoc_list.each do |assoc|
        _perform_erase_dependents assoc
      end
    end
  end
end

#wait_for_no_dependents(*assoc_list, erase_if_found: false) ⇒ Object

if child models don’t include Finalizers::Model, but are self-deleting (perhaps they represent an in-progress work task and are deleted when finished), then use wait_for_no_dependents to defer destroying the current model until the children are gone. if they are not self-deleting, use standard options like dependent: :destroy or :delete_all. finally, if children do include Finalizers::Model, use erase_dependents instead.



84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'app/models/finalizers/model.rb', line 84

def wait_for_no_dependents(*assoc_list, erase_if_found: false)
  add_finalizer prepend: true do
    assoc_list.each do |assoc|
      proxy = send(assoc)
      # has_many's :dependent checks use .size, so match that here
      #   .size uses the cache_counter column, if available, else queries the db
      if proxy.respond_to?(:size)
        count = proxy.size
        _perform_erase_dependents assoc if erase_if_found && count > 0 && proxy.not_deleted.any?
      elsif proxy
        count = 1
        _perform_erase_dependents assoc if erase_if_found && !proxy.deleted?
      else
        count = 0
      end
      if count > 0
        raise RetryJobError, "#{self.class.name} #{id} still has #{count} dependent #{assoc}"
      end
    end
  end
end