[英]Integer validation with exact 10 digits in migrations
嘗試在數據庫級別寫入電話號碼驗證,這將需要精確的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位數字提交到數據庫,也不要少提交。
size
或limit
選項將不起作用。 例如limit = 9,但是我們仍然可以保存長度= 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.