Sha256: 509571c9e383925dd46a8dee76810c111846f4af5433a100919aed2737e14f3f

Contents?: true

Size: 1.11 KB

Versions: 3

Compression:

Stored size: 1.11 KB

Contents

module ActiveRecord
  # This error is raised when trying to destroy a parent instance in N:1 or 1:1 associations
  # (has_many, has_one) when there is at least 1 child associated instance.
  # ex: if @project.tasks.size > 0, DeleteRestrictionError will be raised when trying to destroy @project
  class DetailedDeleteRestrictionError < ActiveRecordError #:nodoc:
    def initialize(name, record)
      @name = name
      @record = record
      super(basic_message)
    end

    def basic_message
      name = @name.to_s.gsub('_', ' ')
      assoc = @record.send(@name)
      count = assoc.respond_to?(:count) ? assoc.count : (assoc ? 1 : 0)
      if count == 1
        "Cannot delete record because dependent #{name} exists"
      else
        "Cannot delete record because #{count} dependent #{name.pluralize} exist"
      end
    end

    def detailed_message
      count = @record.send(@name).count
      examples = @record.send(@name).all(:limit => 5).map{|o| "#{o.id}: #{o.to_s}"}
      examples[4] = "...and #{count - 4} more" if count > 5
      basic_message + "\n\n\nThese include:\n#{examples.join("\n")}"
    end
  end
end

Version data entries

3 entries across 3 versions & 2 rubygems

Version Path
dependent_restrict-0.1.1 lib/dependent_restrict/delete_restriction_error.rb
dependent_restrict-0.1.0 lib/dependent_restrict/delete_restriction_error.rb
dependent_protect-0.0.6 lib/dependent_protect/delete_restriction_error.rb