Class: ActiveRecord::PostgresEnum::EnumValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/active_record/postgres_enum/enum_validator.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.enum_values(attr_id, type, connection) ⇒ Object



6
7
8
9
10
11
12
13
# File 'lib/active_record/postgres_enum/enum_validator.rb', line 6

def self.enum_values(attr_id, type, connection)
  @enums ||= {}
  return @enums[attr_id] if @enums.key?(attr_id)

  @enums[attr_id] ||= connection.enum_types.fetch(type.to_sym) do
    raise "Enum `#{type}` not found in a database #{connection}"
  end
end

Instance Method Details

#validate_each(object, attribute, value) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/active_record/postgres_enum/enum_validator.rb', line 15

def validate_each(object, attribute, value)
  enum_type = enum_type(object, attribute)
  attr_id = "#{object.class.name}##{attribute}"

  return if self.class.enum_values(attr_id, enum_type, object.class.connection).include?(value)

  object.errors.add(
    attribute,
    options[:message] || :invalid_enum_value,
    value: value,
    type: enum_type
  )
end