Class: DatabaseValidations::DBPresenceValidator

Inherits:
ActiveRecord::Validations::PresenceValidator
  • Object
show all
Defined in:
lib/database_validations/lib/db_belongs_to/db_presence_validator.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ DBPresenceValidator

Returns a new instance of DBPresenceValidator.



12
13
14
15
16
17
# File 'lib/database_validations/lib/db_belongs_to/db_presence_validator.rb', line 12

def initialize(options)
  super(options)

  @association = attributes.first
  @foreign_key = options[:foreign_key]
end

Instance Attribute Details

#associationObject (readonly)

Returns the value of attribute association.



10
11
12
# File 'lib/database_validations/lib/db_belongs_to/db_presence_validator.rb', line 10

def association
  @association
end

#foreign_keyObject (readonly)

Returns the value of attribute foreign_key.



10
11
12
# File 'lib/database_validations/lib/db_belongs_to/db_presence_validator.rb', line 10

def foreign_key
  @foreign_key
end

Class Method Details

.kindObject

This is a hack to simulate presence validator It’s used for cases when some 3rd parties are relies on the validators For example, required option from simple_form checks the validator



6
7
8
# File 'lib/database_validations/lib/db_belongs_to/db_presence_validator.rb', line 6

def self.kind
  :presence
end

Instance Method Details

#validate(record) ⇒ Object

The else statement required only for optional: false



20
21
22
23
24
25
26
27
28
# File 'lib/database_validations/lib/db_belongs_to/db_presence_validator.rb', line 20

def validate(record)
  if record._database_validations_fallback
    super
  else
    return unless record.public_send(foreign_key).blank? && record.public_send(association).blank?

    record.errors.add(association, :blank, message: BelongsToOptions::VALIDATOR_MESSAGE)
  end
end