Forum: Ruby on Rails Rails Models: Validation!

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.
Cdac981269f584bab28bae40863268f2?d=identicon&s=25 (Guest)
on 2007-03-07 10:23
(Received via mailing list)

I'm reading "Agile Web Development 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

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 Thomas 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
58c6efb8466b9f85155fe6aa9fc37fce?d=identicon&s=25 Chris T (Guest)
on 2007-03-07 12:36
(Received via mailing list) 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
This topic is locked and can not be replied to.