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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With