Reputation: 397
There is an Article
table in my Rails app, but in this table, there are hundreds of records that being transferred form and old website, so the table looks like this:
1...700 (now use index) ...empty... 1001...3000 (old articles ids)
if I generate a new article, article id will be 701
.
But I can't check whether the article id has been used or not until I process @article.save
.
A temporary solution is: displaying the ID
column, when a user generates result error, then they enter id+1
and try to save.
How can I check this status automatically?
The condition is:
If the article id has been used, then check id+1, until finding an id that can be used?
Upvotes: 0
Views: 97
Reputation: 84124
Postgres uses a sequence to pick the next value for your id column. It sounds like your import process is not updating the sequence. You can update the value of the sequence with something like this
select setval('articles_id_seq', (SELECT MAX(id) FROM articles));
You can check the name of the sequence from psql with \d articles
.
Upvotes: 1
Reputation: 2783
If i was you, I would create and immediately delete all records up to the ids you have already hardcoded from your old app. this way you will continue new ids from the place where old app has left off. I see no reason to make your code more complicated than it needs to be because of the issue that will be literally one-off event.
rails c
(700..3000).each do
a = Article.create() rescue nil #when you hit the ids that are already in the database
puts a.try(:id)
a.delete
end
Upvotes: 0