DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Defining A Custom Validates In Rails

10.19.2005
| 16464 views |
  • submit to reddit
        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
    

Comments

Snippets Manager replied on Sun, 2007/02/25 - 8:09pm

I am fairly new to RoR and that is why I was so happy with your snipplet, but there seems to be a problem with this code when the value that is checked isn't actually present. I have an Item object with a price and I check the price with validates_presence_of :price before I do this function. Unfortunattely this function is called no matter what. How can I fix this?