gpt4 book ai didi

ruby-on-rails - 将属性验证为仅整数

转载 作者:数据小太阳 更新时间:2023-10-29 07:04:13 25 4
gpt4 key购买 nike

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,它没有达到上面的验证条件,即使我发送 float ,验证条件怎么可能为真.(Rails 新手,希望这个问题有意义)。

最佳答案

检查 validates_numericality_of 中整数的功能已经存在- 只需将 :only_integer 设置为 true

您可以根据 rails documentation 在事件记录模型中使用验证.

validates :your_column_name, numericality: { only_integer: true }

关于ruby-on-rails - 将属性验证为仅整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28713867/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com