views:

468

answers:

2

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

+2  A: 
  1. Give the error message, it's a lot easier to diagnose the problem.
  2. Use built in validations, learn how to change their messages (:message parameter to validates_numericality_of)
  3. if @test < 0 should rather be if @test.to_i < 0
Bragi Ragnarson
if i use built in validations, the field name also coming along with the error messageexamplestest: is not validi don't want test: to be displayedso i turned towards user defined validate
Senthil Kumar Bhaskaran
and the error is undefined method `to_i' for #<Money:0xb57d1e90>
Senthil Kumar Bhaskaran
It seems that you are calling to_i on the Money object instead on the test attribute of a Money object. Hopefully this helps.
SamChandra
+1  A: 

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.

SamChandra
the problem still arises,local variable and instance variable acting same here
Senthil Kumar Bhaskaran
Can you give me more information on the error that you get.
SamChandra