Writing a rails validator with integer

Posted by user297008 on Stack Overflow See other posts from Stack Overflow or by user297008
Published on 2010-03-19T00:21:54Z Indexed on 2010/03/19 2:51 UTC
Read the original article Hit count: 391

Filed under:
|
|
|

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

© Stack Overflow or respective owner

Related posts about rails

Related posts about ruby