class ActiveModel::Validations::PresenceOfAtLeastOneOfValidator

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

Constants

ERROR_MESSAGE

Public Class Methods

new(options = {}) click to toggle source
Calls superclass method
# File lib/activemodel/extra_validations/presence_of_at_least_one_of.rb, line 9
def initialize(options = {})
  super(options)

  check_validity!
end

Public Instance Methods

validate(record) click to toggle source
# 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

Private Instance Methods

add_errors_to_record(record) click to toggle source
# File lib/activemodel/extra_validations/presence_of_at_least_one_of.rb, line 25
def add_errors_to_record(record)
  attribute_names.each do |attribute_name|
    record.errors.add(attribute_name, error_message_or_error_type, one_of: attribute_names)
  end
end
attribute_names() click to toggle source
# File lib/activemodel/extra_validations/presence_of_at_least_one_of.rb, line 35
def attribute_names
  options[:attributes]
end
check_validity!() click to toggle source
# File lib/activemodel/extra_validations/presence_of_at_least_one_of.rb, line 31
def check_validity!
  raise ArgumentError, ERROR_MESSAGE unless options[:attributes].many?
end
error_message_or_error_type() click to toggle source
# File lib/activemodel/extra_validations/presence_of_at_least_one_of.rb, line 39
def error_message_or_error_type
  options[:message] || :presence_of_at_least_one_of
end