# Rails Models: Validation!

**URL:** <https://www.ruby-forum.com/t/rails-models-validation/87988>\
**Category:** Rails\
**Created:** [March 7, 2007, 10:23am UTC](https://www.ruby-forum.com/t/rails-models-validation/87988 "2007-03-07T10:23:41Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [March 7, 2007, 10:23am UTC](https://www.ruby-forum.com/t/rails-models-validation/87988/1 "2007-03-07T10:23:41Z")

</div>

Hi!

I’m reading “Agile Web D. with Rails” at the moment, but now  
I came to a problem that I can not solve myself.  
In a Model called “Product” I want to validate the presence of a  
decimal. I do that with “validates\_presence\_of”. And, additionally, I  
want to validate that the decimal typed in by the user is greater than  
zero. I do that with a protected method called “validate”.  
Here is the code for the method “validate”:  
def validate  
errors.add(:price, “should be at least 0.01”) if price.nil? ||  
price \< 0.01  
end

But here comes the problem: If the user does not type in a value, this  
case should be caught by “price.nil?”, because there will be no value  
be set for it and so it won’t be set at all (i hope that is  
right! 😉 ). And if there is a value, the “if” should check if the  
price is smaller than 0.01! And if Mister Dave T. says so, it  
should work this way (This code is in his book!)! But the reality  
looks like the following: (Browser rendered the following, when i  
tried to let the field empty)  
“undefined local variable or method ` price’ for #Product:0x2649c08”

It looks like this does not work (the if-checking thing)!

Has anyone a suggestion how i could fix that so the behaviour will be  
exactly like I expect it…?!?  
And: Does Rails first execute “validates\_presence\_of” (and sisters and  
brothers) or “validate” (which I wrote myself)??

Thanks and Greetings from Austria,

- dominik

---

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [March 7, 2007, 12:36pm UTC](https://www.ruby-forum.com/t/rails-models-validation/87988/2 "2007-03-07T12:36:08Z")

</div>

removed\_email\_address@domain.invalid wrote:

> ```
> errors.add(:price, "should be at least 0.01") if price.nil? ||
> 
> ```
> 
> tried to let the field empty)
> 
> - dominik
> 
> >

I think the prob is not with the validate method but with the  
Product#price attribute. Can you just check that the attribute exists on  
this model. Go into the console and try Product.new.respond\_to?(:price)
