I was trying to write a validation for Rails to ensure that a price entered on a form was greater than zero. It works…sort of. The problem is that when I run it, val
is turned into an integer, so it thinks that .99 is less than .1. What's going on, and how should 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