Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

:greater_than_or_equal_to in validates_numericality_of only partially working in rails 3.1

We are using the following to check if stock_qty (an integer or a float. Could be zero but not nil) is greater or equal to zero:

validates_numericality_of :stock_qty, :greater_than_or_equal_to => 0
validates_numericality_of :stock_qty, :less_than_or_equal_to => :in_qty, :if => Proc.new { |part| !part.in_qty.nil? }

:in_qty is a column in part model. This validation should allow positive or 0 for :stock_qty. The problem is that the rspec failed if :stock_qty is assigned zero. I noticed that :less_than_or_equal_to only allowed less_than and did not allow equal_to. Is there a way to validate the >= or <= in rails 3.1? Or what may go wrong with our validation code above. Thanks so much.

like image 479
user938363 Avatar asked Apr 17 '12 20:04

user938363


2 Answers

try adding :only_integer => true like so:

validates_numericality_of :stock_qty, :only_integer => true, :greater_than_or_equal_to => 0

EDIT

if this needs to pass when stock_qty is nil or zero you need to change your code to this:

validates_numericality_of :stock_qty, :allow_nil => true, :greater_than_or_equal_to => 0
validates_numericality_of :stock_qty, :allow_nil => true, :less_than_or_equal_to => :in_qty, :if => Proc.new { |part| !part.in_qty.nil? }
like image 180
Eric Sites Avatar answered Sep 20 '22 13:09

Eric Sites


validates :stock_qty, :numericality => { :only_integer => true, :greater_than_or_equal_to => 0 }

it works in my 3.1 app, in my case I have price, and when I update or add the product wthout price I got the "it's not a number" error, or something like that, but I can put a 0 in price column and it updates just fine. hope this helps.

:greater_than_or_equal_to – Specifies the value must be greater than or equal to the supplied value. The default error message for this option is “must be greater than or equal to %{count}”.

http://guides.rubyonrails.org/active_record_validations_callbacks.html

like image 20
rmagnum2002 Avatar answered Sep 19 '22 13:09

rmagnum2002