Class: ActiveRecord::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/prevent_destroy_if_any.rb

Class Method Summary collapse

Class Method Details

.prevent_destroy_if_any(*association_names) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/prevent_destroy_if_any.rb', line 4

def self.prevent_destroy_if_any(*association_names)
  before_destroy do |model|
    associations_present = []

    association_names.each do |association_name|
      association = model.send association_name
      if association.class == Array
        associations_present << association_name if association.any?
      else
        associations_present << association_name if association
      end
    end

    if associations_present.any?
      errors.add :base, "Cannot delete #{model.class.model_name.human.downcase} while #{associations_present.join ', '} exist"
      return false
    end

  end
end