Class: ActiveModel::Validations::PresenceOfAtLeastOneOfValidator

Inherits:
Validator
  • Object
show all
Defined in:
lib/activemodel/extra_validations/presence_of_at_least_one_of.rb

Overview

Validates whether at least one of the specified attributes is present.

Constant Summary collapse

ERROR_MESSAGE =
'This validator requires at least two arguments.'.freeze

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ PresenceOfAtLeastOneOfValidator

Returns a new instance of PresenceOfAtLeastOneOfValidator.



9
10
11
12
13
# File 'lib/activemodel/extra_validations/presence_of_at_least_one_of.rb', line 9

def initialize(options = {})
  super(options)

  check_validity!
end

Instance Method Details

#validate(record) ⇒ Object



15
16
17
18
19
20
21
# File 'lib/activemodel/extra_validations/presence_of_at_least_one_of.rb', line 15

def validate(record)
  at_least_one_present = attribute_names.any? do |attribute_name|
    record.attributes[attribute_name.to_s].present? || !record.attributes[attribute_name.to_s].nil?
  end

  add_errors_to_record(record) unless at_least_one_present
end