Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: force specific id for new record (or change id of existing)

Due to an error that deleted a user in our Rails app I'm trying to force another user record into the old records ID.

$ rails console
> User.find(2)
ActiveRecord::RecordNotFound: Couldn't find User with 'id'=2
> replacer = User.find(5)
=> #<User id: 5, created_at: [omitted for brevity ...] >
replacer.id = 2
=> 2
replacer.save
=> true
> User.find(2)
ActiveRecord::RecordNotFound: Couldn't find User with 'id'=2
> User.find(5)
ActiveRecord::RecordNotFound: Couldn't find User with 'id'=5
> replacer
=> #<User id: 2, created_at: [omitted for brevity ...] >
> replacer.valid?
=> true

What's going on here?

like image 435
Meltemi Avatar asked Dec 05 '25 10:12

Meltemi


1 Answers

Your update statement is constructed using the id of the in memory object, which you have set to 2. You can't update a record that doesn't exist.

If you want to stay in active record land I think you can do: User.update(5, id: 2)

Failing that, you can definitely do it in SQL. UPDATE users SET id = 2 WHERE id = 5.

like image 115
Derek Prior Avatar answered Dec 07 '25 00:12

Derek Prior



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!