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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With