如何仅用Ruby on Rails对模型属性进行整数验证?

更新于
2026-10-09 19:21:27
1阅读来源:SEO资源
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计177个文字,预计阅读时间需要1分钟。

如何仅用Ruby on Rails对模型属性进行整数验证?

rubyproduct.rb 模型文件:class Product

def price=(input) input.delete!('$') s end

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在活动记录模型中使用验证.

如何仅用Ruby on Rails对模型属性进行整数验证?

validates :your_column_name, numericality: { only_integer: true }

本文共计177个文字,预计阅读时间需要1分钟。

如何仅用Ruby on Rails对模型属性进行整数验证?

rubyproduct.rb 模型文件:class Product

def price=(input) input.delete!('$') s end

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在活动记录模型中使用验证.

如何仅用Ruby on Rails对模型属性进行整数验证?

validates :your_column_name, numericality: { only_integer: true }