Forum: Ruby on Rails Adding custom validations to active record

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
sa 1. (Guest)
on 2009-02-22 11:24
Hi - I want to add my own validation to a rails app, and need help
making it global to my app. Basically, the validation makes sure a
number is positive - I found this code on the at

module CustomValidations

  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


I want to use it in my models like any other validation:

class SomeModel < ActiveRecord::Base
  validates_positivity_of :some_number, :another_number

I saved it in lib/custom_validations.rb, and tried including it in the
top of my environment.rb to extend AR:

include 'custom_validations'
class ActiveRecord::Base
  include CustomValidations

#.. rest of file

Sadly, this won't work. How do I make rails identify this module and use
it properly?
Phlip (Guest)
on 2009-02-22 11:31
(Received via mailing list)
sa 125 wrote:

> Sadly, this won't work.
Always include even a snip of the error message you got. After your
writeup, just claiming "won't work" leaves us bereft of closure!

However, the top of environment.rb might be before "require
That means 'class' would introduce 'ActiveRecord', leaving 'Base' as a
identifier. If so, move it to the bottom!

sa 1. (Guest)
on 2009-02-22 11:44
my bad. I moved that block to the bottom of the environment.rb file,
after the "end" of the Rails::Initializer code, but got this error:

NoMethodError (undefined method 'validates_positivity_of' for
   /../active_record/base.rb:1833:in 'method missing'

I tried loading this method though ./script/console:
irb> include CustomValidations
irb> validates_positivity_of 2
NoMethodError: undefined method 'validates_each' for #<object..>
   from /../lib/custom_validations.rb:6:in 'validates_positivity_of'

Now I'm not even sure if the function works properly.
Maurício L. (Guest)
on 2009-02-22 13:56
(Received via mailing list)
It isn`t include in your case, it`s extend:

include 'custom_validations'
class ActiveRecord::Base
 extend CustomValidations

Here's a better explanation why ->

Maurício Linhares (pt-br) |

On Sun, Feb 22, 2009 at 6:24 AM, sa 125
This topic is locked and can not be replied to.