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).
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With