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”:
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 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,