Over a million developers have joined DZone.

Defining A Custom Validates In Rails

DZone's Guide to

Defining A Custom Validates In Rails

Free Resource
in the model:

class User < ActiveRecord::Base
  require 'validations'

  validates_positive_or_zero :number

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

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}