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.
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? }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With