roa*_*ror 7 ruby activerecord ruby-on-rails
product.rb模型文件:
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
Run Code Online (Sandbox Code Playgroud)
我希望股票只是整数.当我提交浮点值为34.48的股票然后在服务器日志中的插入sql cmd时,我只看到34,并且它没有达到上面的验证条件,即使我发送浮点数,验证条件是如何可能是怎么回事? (对rails很新,希望这个问题有意义).
Bra*_*rth 12
已存在用于检查整数的功能validates_numericality_of- 只需设置:only_integer为true
您可以根据rails文档在活动记录模型中使用验证.
validates :your_column_name, numericality: { only_integer: true }
Run Code Online (Sandbox Code Playgroud)