Reputation: 7451
How do I change
validates_numericality_of :test, :greater_than_or_equal_to=>0
into validate form
I tried only character and nil values. I need to check also it must be greater than 0
validate change_test
def change_test
if @test.nil?
errors.add_to_base('Hi Test should be only number')
end
end
and also I tried like this,
validate change_test
def change_test
if @test.nil?
errors.add_to_base('Hi Test should be only number')
else
if @test < 0
errors.add_to_base('The number should be greater than or equal to 0')
end
end
end
but it is result in error
Please help to solve this problem
thanks all
Upvotes: 0
Views: 2780
Reputation: 1185
Your code need to be changed to:
validate :change_test
def change_test
if test.nil?
errors.add_to_base('Hi Test should be only number')
end
end
There are 2 problem with your code:
1. The validate method need to use symbol as the parameter.
2. I am assuming test is the attribute, you should not use @ symbol.
So for the last part of the code, it should be:
class Money < ActiveRecord::Base
validate :change_test
# We are validating an attribute of the Money model called test
def change_test
# This is to test for nil value which is empty string
if test.blank?
errors.add_to_base('Hi Test value cannot be empty')
end
# This is to make sure value is greater than or equal to 0
if test.to_i < 0
errors.add_to_base('The number should be greater than or equal to 0')
end
end
end
Please note that test is not an object. It is an attribute in the model class.
I hope this helps.
Upvotes: 1
Reputation: 523
:message
parameter to validates_numericality_of
)if @test < 0
should rather be if @test.to_i
< 0Upvotes: 2