ADZ 學習筆記

Ruby/Rails, Startup, Life

rails - use unsigned integer in rails migration

| Comments

Sometimes, we want to use unsigned integer or float data type in mysql, like auto increment id or price .. etc, but rails migration does not support yet.

There are 2 ways to use unsigned integer/float in your migration file.

1. define data type directly

your_migration.rb
create_table :products, :id => false do |t|
  t.column :id, 'INT UNSIGNED NOT NULL AUTO_INCREMENT, PRIMARY KEY (id)'
  t.string :name
  t.column :price, 'INT UNSIGNED', null: false, default: 0
end

add_column :products, :qty, 'INT UNSIGNED', null: false, default: 0

you can define date type directly, but it will break the migration design (use interface to define schema), and it looks awful in a way.

2. [gem] activerecord-mysql-unsigned

Recently I found a gem called activrecord-mysql-unsigned, which supports unsigned integer in migration for mysql.

your_migration.rb
create_table :users, force: true do |t|
    t.string  :name, null: false
    t.integer :age,  null: false, unsigned: true
end

change_column :users, :age, :integer, null: false, unsigned: false

The lastest version of this gem only supports integer date type, therefore if you want to use decimal with unsigned, you are welcome to use my temporary fork.

https://github.com/afunction/activerecord-mysql-unsigned

Comments

comments powered by Disqus