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:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}