Over a million developers have joined DZone.

Defining A Custom Validates In Rails

·
in the model:


class User < ActiveRecord::Base
  require 'validations'

  validates_positive_or_zero :number
  
end


in /lib/validations.rb:


def validates_positive_or_zero(*attr_names)
  configuration = { :message => "Cannot be negative" }
  configuration.update(attr_names.pop) if attr_names.last.is_a?(Hash)
  validates_each attr_names do |m, a, v| m.errors.add(a, configuration[:message]) if v<0 end
end
Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}