Module: ActiveRecord::Validations::ClassMethods

Defined in:
lib/enum/validations.rb

Instance Method Summary collapse

Instance Method Details

#validates_columns(*column_names) ⇒ Object

Automatically validates the column against the schema definition for nullability, format, and enumerations. Handles integers, floats, enumerations, and string limits.

Usage: validates_columns :severity, :name



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/enum/validations.rb', line 10

def validates_columns(*column_names)
  begin
    cols = columns_hash
    column_names.each do |name|
      col = cols[name.to_s]
      raise ArgumentError, "Cannot find column #{name}" unless col
      
      # test for nullability
      validates_presence_of(name) if !col.null
      
      # Test various known types.
      case col.type
      when :enum
        validates_inclusion_of name, :in => col.limit, :allow_nil => true
        
      when :integer, :float
        validates_numericality_of name, :allow_nil => true
        
      when :string
        if col.limit
          validates_length_of name, :maximum => col.limit, :allow_nil => true
        end
      end
    end
  rescue ActiveRecord::StatementInvalid=>e
    raise e unless e.message.include?("42S02") # swallow the exception if its for a missing table
  end
end