Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add an auto generated ID to an existing table?

I have a table in my schema that does not have an auto generated ID primary key because I deactivated that option when creating it. Is there a way to put a new column ID that is auto incremented in my table?

like image 677
aplneto Avatar asked Nov 28 '25 02:11

aplneto


2 Answers

if you don't want to Add new migration, also if there is not much more data which is most useful, than rails Also provide functionality to DOWN Migration.

rake db:migrate:down VERSION=20190204205537

'20190204205537' this should be your migration version

it will 'DOWN' your migration, than you can edit it, i mean remove the PRIMARY KEY false. and simply run

rake db:migrate

I Hope this may help to you. Thank you.

like image 61
Ketan Mangukiya Avatar answered Nov 29 '25 18:11

Ketan Mangukiya


Yes, generate a migration with primary_key:

rails g migration add_id_to_my_tables id:primary_key

That will produce a change with add_column:

def change
  add_column :my_tables, :id, :primary_key
end
like image 43
CAmador Avatar answered Nov 29 '25 18:11

CAmador