Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 370
manu_v Avatar asked Apr 04 '11 09:04

manu_v


People also ask

How do I migrate a specific migration in Rails?

To run a specific migration up or down, use db:migrate:up or db:migrate:down . The version number in the above commands is the numeric prefix in the migration's filename. For example, to migrate to the migration 20160515085959_add_name_to_users. rb , you would use 20160515085959 as the version number.

What Rails db Migrate?

Rails Migration allows you to use Ruby to define changes to your database schema, making it possible to use a version control system to keep things synchronized with the actual code. Teams of developers − If one person makes a schema change, the other developers just need to update, and run "rake migrate".

What does Rails generate migration do?

Migrations are a feature of Active Record that allows you to evolve your database schema over time. Rather than write schema modifications in pure SQL, migrations allow you to use a Ruby DSL to describe changes to your tables.


2 Answers

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)

like image 170
KenB Avatar answered Sep 23 '22 13:09

KenB


 def self.up     add_column("admin_users", "username", :string, :limit => 25)  end   def self.down     remove_column("admin_users", "username")  end 
like image 38
ceth Avatar answered Sep 22 '22 13:09

ceth