Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating an attribute to be an integer only

product.rb model file:

class Product < ActiveRecord::Base
  validates_numericality_of :price
  validates_numericality_of :stock, if: Proc.new { |p| (p.stock.is_a? Integer and p.stock >= 0) ? true : false }

  def price=(input)
    input.delete!("$")
    super
  end
end  

I want stock to be integer only. When I submit stock with float value say 34.48 then in Insert sql cmd in server log, I see 34 only, and it doesn't hit the validation condition above, how is this possible that the validation condition is being true even i send float number.(new to rails, hoping this question makes sense).

like image 993
roarfromror Avatar asked Feb 25 '15 07:02

roarfromror


1 Answers

The functionality already exists to check for an integer in validates_numericality_of - just set :only_integer to true

You can use the validation in your active record models as per the rails documentation.

validates :your_column_name, numericality: { only_integer: true }
like image 140
Brad Werth Avatar answered Nov 03 '22 21:11

Brad Werth