Limit integer size when migrating Rails

How do I specify an integer size limit in a Rails 4 migration? (My database is PostgreSQL.)

I have fields for phone_number

which must be 8 digits long. If I specify :limit => 8

then it is the byte size, not the length of the numbers.

Is there a way to do this?

+3


source to share


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


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







All Articles