Sql – Rails : migration for creating a fixed-length char(12) column


What is the best way to define a fixed-length SQL column (CHAR(12) for instance) through a Rails migration ?

Why this should not handled by the model is because of the performance of char() vs varchar(), and I'd like to avoid injecting raw SQL in the database.

Edit : I know the :limit modifier, however the field is still varchar (which is bad for performance) and does not allow a minimum size.

Best Solution

If Rails doesn’t understand the column type, it’ll pass it straight through to the database. So if you want a char instead of varchar, just replace:

t.column :token, :string


t.column :token, "char(12)"

Of course, this may or may not make your migrations non-portable to another database.

(credit to http://laurelfan.com/2010/1/26/special-mysql-types-in-rails-migrations)