Module: PreventDestroy::ClassMethods

Defined in:
lib/prevent_destroy.rb

Instance Method Summary collapse

Instance Method Details

#prevent_destroy_if_has_children(*args) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/prevent_destroy.rb', line 9

def prevent_destroy_if_has_children *args
  
  define_method(:children_to_check) { args }
  
  before_destroy do |record|
    found = []
    if record.children_to_check.any?
      record.children_to_check.each { |search| found << search.to_s.underscore.humanize.downcase if record.send(search).any? }
    end
    if found.any?
      record.errors.add(:base, "The #{self.class.name.underscore.humanize.downcase} cannot be deleted as it contains #{found.to_sentence}")
      false
    end
  end
end