Rabu, 17 November 2010

[shared] Unsigned int support for migration

currently rails only allow signed int for migration, but for best practice it's better to use unsigned int for some cases

you can force migration to unsigned int by doing something like this

t.column :unsigned_value, "integer unsigned"

but that kinda ugly to see.
luckily rob anderton (thewebfellas.com) already created monkey patch to add unsigned support: http://thewebfellas.com/assets/2008/9/30/active_record_unsigned.rb

the patch will add :unsigned option in migration so you can do something like this:

t.integer :unsigned_value, :unsigned => true

furthermore the patch will make default table id and foreign key to unsigned int(11), but make sure to use t.references to create foreign key or simply use :unsigned => true

important things:

- for existing project this patch might break table relation because it will create unsigned int foreign key but the primary key might be signed int from old migration
- some plugin like role_requirement will generate migration that using t.integer for foreign key instead of t.references, you need to change this manually
- the patch will only change mysql adapter, so it will not work for other adapter

2 komentar:

  1. Could you split out the unsigned primary key feature from the unsigned integer support feature? I would like the ability to use unsigned integers, but I do not want unsigned primary keys.

  2. The patch explained thoroughly in the original article here: http://thewebfellas.com/blog/2008/6/2/unsigned-integers-for-mysql-on-rails

    simply take only the code you need for your own patch :)