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 o开发者_Go百科f 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.
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)
def self.up
add_column("admin_users", "username", :string, :limit => 25)
end
def self.down
remove_column("admin_users", "username")
end
You can use string type with limit option in your migration file like this:
t.string :name, :limit => 12, :null => false
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
精彩评论