Writing a relational validator with an integer

I tried to write validation for Rails to ensure that the price entered on the form is greater than zero. It works ... sort of. The problem is that when I run it, val turns into an integer, so it thinks .99 is less than .1. What happens and how do I fix the code?

 class Product < ActiveRecord::Base protected def self.validates_greater_than_zero(*attr_names) validates_each(attr_names) do |record, attr, val| record.errors.add(attr, "should be at least 0.01 (current val = #{val.to_f})") if val.nil? || val < 0.01 end end public validates_presence_of :title, :description, :image_url validates_numericality_of :price validates_greater_than_zero :price end 
+4
source share
2 answers

If the original string value is passed as an integer, it is rounded down. Thus, “0.99” is rounded to 0, which is obviously less than 0.01. You should compare with the source string, which you can get from the <attr>_before_type_cast .

Something like this should work:

 validates_each(attr_names) do |record, attr, val| if record.send("#{attr}_before_type_cast").to_f < 0.01 record.errors.add(attr, "error message here") end end 
+1
source

You can change

 validates_numericality_of :price 

to

 validates_numericality_of :price, :greater_than_or_equal_to => 0.01 

seems to do what your validates_greater_than_zero validator wants to do.

+1
source

Source: https://habr.com/ru/post/1304530/


All Articles