How do I specify a limit on an integer size in a Rails 4 migration? (My database is PostgreSQL.)
I have fields for phone_number
, which should be 8 digits long. If I specify :limit => 8
, then that is byte size rather than the length of the numbers.
Is there a way to do this?
You're going about this all wrong. A phone number is not a number at all, a phone number is a string that contains (mostly) digit characters. You don't do anything numeric – such as arithmetic – with phone numbers so they're not numbers, they're strings.
Make your phone_number
column a string of length eight:
t.string :phone_number, limit: 8
and clean it up and validate the format in your model:
before_validation :clean_up_phone_number
validates :phone_number,
format: { with: /\A\d{8}\z/ },
length: { maximum: 8 },
allow_nil: true
def clean_up_phone_number
# Do whatever you want or need to strip out spaces, hyphens, etc. in here
end
Or better with PostgreSQL, don't worry about the size in the database at all and use t.string :phone_number
. The size limit just adds pointless overhead and using a plain varchar
rather than a varchar(8)
makes it easier to allow for different phone number formats (area codes, extensions, international numbers, ...) later.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With