Limit integer size when migrating Rails
2 answers
You're doing it all wrong. A phone number is not a number at all, a phone number is a string containing (mostly) numbers. You don't do anything numeric - like arithmetic - with phone numbers so they aren't numbers, they are strings.
So, make a column phone_number
eight in length:
t.string :phone_number, :limit => 8
clear and validate the format in your model:
before_validation :clean_up_phone_number
validates :phone_number, :format => { :with => /\A\d{8}\z/ }
def clean_up_phone_number
# Do whatever you want or need to strip out spaces, hyphens, etc. in here
end
+5
source to share
Or you can do it with the mv-core gem ( https://github.com/vprokopchuk256/mv-core ) right in the migration this way (syntax is almost identical to AciveModel :: Validations one):
def change
update_table :users do |table|
t.string :phone_number,
validates: { length: 8,
format: /\A\d{8}\z/,
allow_blank: true,
allow_nil: true }
end
end
And then run this check on your model:
class User < ActiveRecord::Base
enforce_migration_validations
end
By default, your check will be defined as a CHECK constraint for PostgreSQL. But you can change this to trigger a constraint, eg. See the documentation for details.
0
source to share