Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails migration: primary key id with unsigned int(10)

I want to define primary key id as below in my tables through rails migration

id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT

I am using mysql db.

like image 328
Amol Pujari Avatar asked Jan 20 '23 05:01

Amol Pujari


2 Answers

If you prefer to avoid custom SQL in migrations this will work as well:

create_table(:user, id: false,  primary_key: :id) do |t|
  t.primary_key :id, :unsigned_integer, null: false, default: :null, auto_increment: true
  t.string :name
end
like image 108
Matthias Winkelmann Avatar answered Jan 28 '23 17:01

Matthias Winkelmann


Just use #execute with the SQL you need inside your migration.

execute "ALTER TABLE things MODIFY id UNSIGNED(10) NOT NULL AUTO_INCREMENT"

Or if the column doesn't yet exist at all:

execute "ALTER TABLE things ADD COLUMN id UNSIGNED(10) NOT NULL AUTO_INCREMENT PRIMARY KEY"

That should work fine. I think in your migrations it's fine to drop down to pure SQL, and in many cases it's necessary.

like image 25
d11wtq Avatar answered Jan 28 '23 18:01

d11wtq