Senthil Kumar Bhaskaran
Senthil Kumar Bhaskaran

Reputation: 7451

How to change validates_numericality_of into validate on rails

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

Answers (2)

Samuel Chandra
Samuel Chandra

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

Bragi Ragnarson
Bragi Ragnarson

Reputation: 523

  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

Upvotes: 2

Related Questions