Validating an attribute to be an integer only

activerecord, ruby, ruby-on-rails

Solution

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 }

Problem

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).

Original source