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?
Asked
Active
Viewed 548 times
3
-
In simplest case you can do hash. Why do you need it to be auto incremented? i.e. Does increment make sense? Possibly [this post](https://stackoverflow.com/questions/1117584/generating-guids-in-ruby) is helpful. – knh190 May 08 '19 at 03:53
-
This new ID column will be the primary key after I remove the current primary key column. I know I could just edit my migration, but I was wondering if there is a way to do it with a new migration file. – aplneto May 08 '19 at 03:56
-
Increment implies that your sequence has a relationship with time, but do you need it? If you only need to identify a table then timeless hash is effective (even more effective when doing some checks bc you can hash on attributes so it contains more information). Also I wonder why do you remove generated ID? It has to be with some reason. – knh190 May 08 '19 at 04:00
-
I don't think it necessarily has to do with time, but since users in my systems can add new resources to the table, the ID column seems like a simple way to identify rows uniquely, even if the information in some of them is identical. – aplneto May 08 '19 at 04:02
2 Answers
2
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

CAmador
- 1,881
- 1
- 11
- 19
2
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.

Ketan Mangukiya
- 360
- 1
- 7
-
Yeah I'll try and edit current migrations if other people haven't ran them on their systems – Mark May 08 '19 at 10:28