Rails 整数大数输入模型验证失败 ("out of range ")
Rails model validation fails on integer big number input ("out of range ")
我的模型中有 Integer 属性,我需要对其进行后端验证(最多应为 7 位数)。
在我的模型中,我做了一些验证,例如:
validates :duration, format: { with: /([0-9]{1,7})/ }
validates :duration, numericality: { less_than_or_equal_to: 9999999 }
这在我尝试将字母放入表格时有效(它 returns 'is not a number' 错误),当我输入有效整数时效果很好(11045555 - returns 'must be less than or equal to 9999999') 但是当我输入非常大的数字时它会崩溃 - 比如说 1104555766666666666。错误是“11045555766666666666 超出 ActiveRecord::Type::Integer 的范围,限制为 4”
当用户输入这么大的数字时,我如何才能避免崩溃?
我用mysql2数据库
您必须声明迁移文件的限制。默认情况下,整数以 4 个字节编码,因此限制为 2147483647
.
如果你想设置一个更大的限制,像这样声明它
add_column :yourtable, :duration, :integer, :limit => 8
8 个字节有 9223372036854775807
个限制。
只需检查 How to specify the size of an integer in the migration script
我的模型中有 Integer 属性,我需要对其进行后端验证(最多应为 7 位数)。 在我的模型中,我做了一些验证,例如:
validates :duration, format: { with: /([0-9]{1,7})/ }
validates :duration, numericality: { less_than_or_equal_to: 9999999 }
这在我尝试将字母放入表格时有效(它 returns 'is not a number' 错误),当我输入有效整数时效果很好(11045555 - returns 'must be less than or equal to 9999999') 但是当我输入非常大的数字时它会崩溃 - 比如说 1104555766666666666。错误是“11045555766666666666 超出 ActiveRecord::Type::Integer 的范围,限制为 4”
当用户输入这么大的数字时,我如何才能避免崩溃?
我用mysql2数据库
您必须声明迁移文件的限制。默认情况下,整数以 4 个字节编码,因此限制为 2147483647
.
如果你想设置一个更大的限制,像这样声明它
add_column :yourtable, :duration, :integer, :limit => 8
8 个字节有 9223372036854775807
个限制。
只需检查 How to specify the size of an integer in the migration script