Adding custom validations to active record


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?


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!



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.


It isnt include in your case, its 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