Search code examples
ruby-on-railspostgresqlactiverecordrails-activerecordrails-migrations

Rails - Specify a fixed length column in DB migration with PostgresSQL


It seems that among column modifiers there's only :limit, which specifies the maximum length of this column. However, what if I want to specify the length to be exact? For example a cellphone number must have 11 digits, so I won't want the user to enter an invalid number. Of course I can also carry out the validation in model logic or even front-end, however it seems to be safer to add a constrain at DB level. Is there a way to achieve this in Rails? Or do I have to use Postgre-specific commands. If so, how?

Thanks!


Solution

  • Rails itself only supports a limited set of constraints. You can run arbitrary SQL commands through execute, though:

    class CreateAddresses < ActiveRecord::Migration
      def change
        create_table(:addresses) do |t|
          t.string :phone_number, null: false
        end
    
        execute "ALTER TABLE addresses ADD CONSTRAINT addresses_phone_length CHECK (length(phone_number) = 11)"
      end
    end