# Adding validations on the fly

**URL:** <https://www.ruby-forum.com/t/adding-validations-on-the-fly/137516>\
**Category:** Rails\
**Created:** [May 13, 2008, 10:29pm UTC](https://www.ruby-forum.com/t/adding-validations-on-the-fly/137516 "2008-05-13T22:29:32Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![kyku](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/34f0e0/32.png) [@kyku](https://www.ruby-forum.com/u/kyku)\
**Post date:** [May 13, 2008, 10:29pm UTC](https://www.ruby-forum.com/t/adding-validations-on-the-fly/137516/1 "2008-05-13T22:29:32Z")

</div>

Hello,

In some situations I’d like to extend single objects with additional  
virtual attributes and validation methods for them, for example:

@foo = Foo.find(param[:id])

class \<\< @foo  
def bar  
nil  
end

validates\_presence\_of :bar  
end

puts @foo.valid?

However, what is puzzling is that this still returns true… Can anyone  
point me at what I’m doing wrong?

---

<div class="post-metadata">

**Author:** ![kyku](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/34f0e0/32.png) [@kyku](https://www.ruby-forum.com/u/kyku)\
**Post date:** [May 14, 2008, 12:13am UTC](https://www.ruby-forum.com/t/adding-validations-on-the-fly/137516/2 "2008-05-14T00:13:11Z")

</div>

On Tuesday 13 May 2008, Krzysztof Wrzalik wrote:

> end
> 
> validates\_presence\_of :bar  
> end
> 
> puts @foo.valid?
> 
> However, what is puzzling is that this still returns true… Can  
> anyone point me at what I’m doing wrong?

Your call to validates\_presence\_of addss a validation on the singleton  
class of @foo where it will never be executed. You’d need to add the  
validation to the class Foo

@foo.class.validates\_presence\_of :bar

but then it would be active for all instances of Foo in the same  
process. Much better to add the validation to the class proper and  
guard it with a condition

class Foo \< ActiveRecord::Base  
validates\_presence\_of :bar, :if =\> …  
end

Michael

–  
Michael S.  
[mailto:removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)  
[http://www.schuerig.de/michael/](http://www.schuerig.de/michael/)
