Module: ActiveItem::Associations

Extended by:
ActiveSupport::Concern
Includes:
ModelLoader
Included in:
Base
Defined in:
lib/active_item/associations.rb

Instance Method Summary collapse

Methods included from ModelLoader

#safe_constantize_model

Instance Method Details

#check_dependent_associationsObject



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/active_item/associations.rb', line 16

def check_dependent_associations
  self.class._associations.each do |name, config|
    next unless config[:type] == :has_many && config[:dependent]

    associated_records = send(name)
    has_records = associated_records.respond_to?(:any?) ? associated_records.any? : false

    next unless has_records

    case config[:dependent]
    when :restrict_with_exception
      raise DeleteRestrictionError.new(name)
    when :restrict_with_error
      error_message = config[:message] || "Cannot delete #{self.class.name} because dependent #{name} exist"
      errors.add(:base, error_message)
      throw(:abort)
    when :destroy
      associated_records.each(&:destroy)
    when :delete_all
      associated_records.each(&:delete)
    when :nullify
      foreign_key = config[:foreign_key]
      associated_records.each { |record| record.update(foreign_key => nil) }
    end
  end
end