Module: SimpleEnum::Validation

Included in:
ClassMethods
Defined in:
lib/simple_enum/validation.rb

Instance Method Summary collapse

Instance Method Details

#validates_as_enum(*attr_names) ⇒ Object

Validates an as_enum field based on the value of it’s column.

Model:

class User < ActiveRecord::Base
  as_enum :gender, [ :male, :female ]
  validates_as_enum :gender
end

View:

<%= select(:user, :gender, User.genders.keys) %>

Configuration options:

  • :message - A custom error message (default: is [:activerecord, :errors, :messages, :invalid_enum]).

  • :on - Specifies when this validation is active (default is :save, other options :create, :update).

  • :if - Specifies a method, proc or string to call to determine if the validation should occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The method, proc or string should return or evaluate to a true or false value.

  • :unless - Specifies a method, proc or string to call to determine if the validation should not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The method, proc or string should return or evaluate to a true or false value.



24
25
26
27
28
29
30
31
32
33
34
# File 'lib/simple_enum/validation.rb', line 24

def validates_as_enum(*attr_names)
  @configuration = { :on => :save }
  @configuration.update(attr_names.extract_options!)      
  attr_names.map! { |e| enum_definitions[e][:column] } # map to column name
  validates_each(attr_names) do |record, attr_name, value|
    enum_def = enum_definitions[attr_name]
    unless send(enum_def[:name].to_s.pluralize).values.include?(value)
      record.errors.add(enum_def[:name], :invalid_enum, :default => @configuration[:message], :value => value)
    end
  end
end