Sha256: 789e3714197b601f8a5c3127e2d916b5d40110f565330f49090d8c6b1ab9a1c7

Contents?: true

Size: 1.13 KB

Versions: 2

Compression:

Stored size: 1.13 KB

Contents

# frozen_string_literal: true

require_relative '../cop'

module ActiveRecord
  module DataIntegrity
    module Validation
      # Checks foreign key presence to the parent table of belongs_to association
      class Presence < ActiveRecord::DataIntegrity::Cop
        def call
          results = validators.map do |validator|
            validator.attributes.map do |attribute|
              valid?(attribute)
            end
          end.flatten

          results.none?(&:!)
        end

        private

        def valid?(attribute)
          column = find_column(attribute)
          return true if column.nil?

          result = !column.null
          progress(result, 'D')
          !column && log("has nullable column #{attribute} with presence validation") unless result
          result
        end

        def validators
          model
            .validators
            .select { |v| v.is_a?(ActiveRecord::Validations::PresenceValidator) }
        end

        def find_column(attribute)
          connection
            .columns(model.table_name)
            .find { |col| col.name == attribute.to_s }
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
activerecord-data_integrity-0.2.1 lib/active_record/data_integrity/cop/validation/presence.rb
activerecord-data_integrity-0.1.0 lib/active_record/data_integrity/cop/validation/presence.rb