Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying Database IDs from Rails Console?

I have a small database and have been adding entries through a Rails page. I "destroyed" one of the entries and now my sequence of IDs are skipping by one. For example, I now have 42 then 44, instead of the obvious: 42, 43, 44.

I was wondering if there was a way to edit the ID number of a new object through the console. I have tried:

record.id = 43
record.save

and

record = record.new
record.attributes = { :id => 43 }

but both didn't work. I'm fairly certain there has to be a console method for this, but I can't seem to find much specific on Google and I probably read the Rails API incorrectly... Would I possibly have to do this through direct SQL in sqlite?

Thanks

like image 803
nmiller Avatar asked Jan 13 '09 02:01

nmiller


1 Answers

The best way to do it is to execute the SQL directly, and solve this temporal glitch in the sequence.

Try accessing the console (ruby script/console) and type:

>> sql = "update records set id=43 where id=44"
>> ActiveRecord::Base.connection.execute(sql)

Where 44 is the newly created object's id, and 43 is the one you were missing in your table

Good luck!

like image 90
Fer Martin Avatar answered Nov 15 '22 15:11

Fer Martin