ruby-on-rails – 仅将属性验证为整数
发布时间:2020-12-17 01:34:36 所属栏目:百科 来源:网络整理
导读: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
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 我希望股票只是整数.当我提交浮点值为34.48的股票然后在服务器日志中的插入sql cmd时,我只看到34,并且它没有达到上面的验证条件,即使我发送浮点数,验证条件是如何可能是怎么回事? (对rails很新,希望这个问题有意义). 解决方法
已存在用于检查
validates_numericality_of 中的整数的功能 – 只需将:only_integer设置为true
您可以根据rails documentation在活动记录模型中使用验证. validates :your_column_name,numericality: { only_integer: true } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |