【问题标题】:Integer validation with exact 10 digits in migrations迁移中精确 10 位的整数验证
【发布时间】:2016-09-06 11:02:18
【问题描述】:

尝试在数据库级别写入电话号码验证,这将需要精确的 10 位数字。

试过了

t.integer :phone, null: false
t.integer :phone, null: false, size: 10
t.integer :phone, null : false, limit: 5

但是没有用。

我的发现

:limit      Numeric Type    Column Size     Max value
1           tinyint         1 byte          127
2           smallint        2 bytes         32767
3           mediumint       3 bytes         8388607
nil, 4, 11  int(11)         4 bytes         2147483647
5..8        bigint          8 bytes         9223372036854775807

当我没有通过限制时,它提交123 并拒绝提交9999999999。由于没有最小值和最大值(2147483647) 的限制。

需要向数据库提交准确的 10 位数字,也不能再少。

【问题讨论】:

    标签: mysql ruby-on-rails ruby-on-rails-4 database-migration


    【解决方案1】:

    sizelimit 选项将不起作用。比如limit = 9,但是我们仍然可以保存一个length = 8的值,这是有道理的。

    只使用活动记录验证怎么样,超级简单:

    validates_length_of :phone, is: 9
    

    为了数据的一致性,我们可以添加一个带约束的迁移

    class AddMyConstraint < ActiveRecord::Migration
      def up
        execute "ALTER TABLE table_name ADD CONSTRAINT check_phone_length CHECK (phone >= 1000000000 AND phone <= 999999999 )"
      end
    
      def down
        execute "ALTER TABLE table_name DROP CONSTRAINT check_phone_length"
      end
    end
    

    【讨论】:

    • 感谢@Hieu,但您的解决方案与模型验证有关。如果我这样做 User.new(phone: 1234567890123).save(validate: false) 它无法验证,所以我也需要在数据库级别进行限制。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-12
    • 2013-12-05
    • 2021-09-27
    • 2010-12-06
    • 1970-01-01
    相关资源
    最近更新 更多