Never been to DZone Snippets before?

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

Defining a custom validates in rails (See related posts)

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 on this post

cbetta posts on Feb 25, 2007 at 19:13
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?

You need to create an account or log in to post comments to this site.


Click here to browse all 4856 code snippets

Related Posts