manu_v
manu_v

Reputation: 1258

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.

Upvotes: 37

Views: 33153

Answers (4)

meoww-
meoww-

Reputation: 1892

For a database specific type, we can now use:

t.column(:column_name, 'char(12)')

And for a complete example:

class Foo < ActiveRecord::Migration
  def change
     create_table :foo do |t|
       t.column(:column_name, 'custom_type')

       t.timestamps
     end
  end
end

Upvotes: 6

KenB
KenB

Reputation: 6757

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

With:

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)

Upvotes: 56

ceth
ceth

Reputation: 45295

 def self.up
    add_column("admin_users", "username", :string, :limit => 25)
 end

 def self.down
    remove_column("admin_users", "username")
 end

Upvotes: 28

Ashish
Ashish

Reputation: 5791

You can use string type with limit option in your migration file like this:

t.string :name, :limit => 12, :null => false

Upvotes: 8

Related Questions